Bitcoin v0.1.3 · 2009-01-12
main.cpp
1// Copyright (c) 2009 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.45#include "headers.h"6#include "sha.h"789101112//13// Global state14//1516CCriticalSection cs_main;1718map<uint256, CTransaction> mapTransactions;19CCriticalSection cs_mapTransactions;20unsigned int nTransactionsUpdated = 0;21map<COutPoint, CInPoint> mapNextTx;2223map<uint256, CBlockIndex*> mapBlockIndex;24const uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");25CBlockIndex* pindexGenesisBlock = NULL;26int nBestHeight = -1;27uint256 hashBestChain = 0;28CBlockIndex* pindexBest = NULL;2930map<uint256, CBlock*> mapOrphanBlocks;31multimap<uint256, CBlock*> mapOrphanBlocksByPrev;3233map<uint256, CDataStream*> mapOrphanTransactions;34multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;3536map<uint256, CWalletTx> mapWallet;37vector<pair<uint256, bool> > vWalletUpdated;38CCriticalSection cs_mapWallet;3940map<vector<unsigned char>, CPrivKey> mapKeys;41map<uint160, vector<unsigned char> > mapPubKeys;42CCriticalSection cs_mapKeys;43CKey keyUser;4445string strSetDataDir;46int nDropMessagesTest = 0;4748// Settings49int fGenerateBitcoins;50int64 nTransactionFee = 0;51CAddress addrIncoming;525354555657585960//////////////////////////////////////////////////////////////////////////////61//62// mapKeys63//6465bool AddKey(const CKey& key)66{67 CRITICAL_BLOCK(cs_mapKeys)68 {69 mapKeys[key.GetPubKey()] = key.GetPrivKey();70 mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();71 }72 return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());73}7475vector<unsigned char> GenerateNewKey()76{77 CKey key;78 key.MakeNewKey();79 if (!AddKey(key))80 throw runtime_error("GenerateNewKey() : AddKey failed\n");81 return key.GetPubKey();82}8384858687//////////////////////////////////////////////////////////////////////////////88//89// mapWallet90//9192bool AddToWallet(const CWalletTx& wtxIn)93{94 uint256 hash = wtxIn.GetHash();95 CRITICAL_BLOCK(cs_mapWallet)96 {97 // Inserts only if not already there, returns tx inserted or tx found98 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));99 CWalletTx& wtx = (*ret.first).second;100 bool fInsertedNew = ret.second;101 if (fInsertedNew)102 wtx.nTimeReceived = GetAdjustedTime();103104 //// debug print105 printf("AddToWallet %s %s\n", wtxIn.GetHash().ToString().substr(0,6).c_str(), fInsertedNew ? "new" : "update");106107 if (!fInsertedNew)108 {109 // Merge110 bool fUpdated = false;111 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)112 {113 wtx.hashBlock = wtxIn.hashBlock;114 fUpdated = true;115 }116 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))117 {118 wtx.vMerkleBranch = wtxIn.vMerkleBranch;119 wtx.nIndex = wtxIn.nIndex;120 fUpdated = true;121 }122 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)123 {124 wtx.fFromMe = wtxIn.fFromMe;125 fUpdated = true;126 }127 if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)128 {129 wtx.fSpent = wtxIn.fSpent;130 fUpdated = true;131 }132 if (!fUpdated)133 return true;134 }135136 // Write to disk137 if (!wtx.WriteToDisk())138 return false;139140 // Notify UI141 vWalletUpdated.push_back(make_pair(hash, fInsertedNew));142 }143144 // Refresh UI145 MainFrameRepaint();146 return true;147}148149bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)150{151 if (tx.IsMine() || mapWallet.count(tx.GetHash()))152 {153 CWalletTx wtx(tx);154 // Get merkle branch if transaction was found in a block155 if (pblock)156 wtx.SetMerkleBranch(pblock);157 return AddToWallet(wtx);158 }159 return true;160}161162bool EraseFromWallet(uint256 hash)163{164 CRITICAL_BLOCK(cs_mapWallet)165 {166 if (mapWallet.erase(hash))167 CWalletDB().EraseTx(hash);168 }169 return true;170}171172173174175176177178179180//////////////////////////////////////////////////////////////////////////////181//182// mapOrphanTransactions183//184185void AddOrphanTx(const CDataStream& vMsg)186{187 CTransaction tx;188 CDataStream(vMsg) >> tx;189 uint256 hash = tx.GetHash();190 if (mapOrphanTransactions.count(hash))191 return;192 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);193 foreach(const CTxIn& txin, tx.vin)194 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));195}196197void EraseOrphanTx(uint256 hash)198{199 if (!mapOrphanTransactions.count(hash))200 return;201 const CDataStream* pvMsg = mapOrphanTransactions[hash];202 CTransaction tx;203 CDataStream(*pvMsg) >> tx;204 foreach(const CTxIn& txin, tx.vin)205 {206 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);207 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)208 {209 if ((*mi).second == pvMsg)210 mapOrphanTransactionsByPrev.erase(mi++);211 else212 mi++;213 }214 }215 delete pvMsg;216 mapOrphanTransactions.erase(hash);217}218219220221222223224225226//////////////////////////////////////////////////////////////////////////////227//228// CTransaction229//230231bool CTxIn::IsMine() const232{233 CRITICAL_BLOCK(cs_mapWallet)234 {235 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);236 if (mi != mapWallet.end())237 {238 const CWalletTx& prev = (*mi).second;239 if (prevout.n < prev.vout.size())240 if (prev.vout[prevout.n].IsMine())241 return true;242 }243 }244 return false;245}246247int64 CTxIn::GetDebit() const248{249 CRITICAL_BLOCK(cs_mapWallet)250 {251 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);252 if (mi != mapWallet.end())253 {254 const CWalletTx& prev = (*mi).second;255 if (prevout.n < prev.vout.size())256 if (prev.vout[prevout.n].IsMine())257 return prev.vout[prevout.n].nValue;258 }259 }260 return 0;261}262263int64 CWalletTx::GetTxTime() const264{265 if (!fTimeReceivedIsTxTime && hashBlock != 0)266 {267 // If we did not receive the transaction directly, we rely on the block's268 // time to figure out when it happened. We use the median over a range269 // of blocks to try to filter out inaccurate block times.270 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);271 if (mi != mapBlockIndex.end())272 {273 CBlockIndex* pindex = (*mi).second;274 if (pindex)275 return pindex->GetMedianTime();276 }277 }278 return nTimeReceived;279}280281282283284285286int CMerkleTx::SetMerkleBranch(const CBlock* pblock)287{288 if (fClient)289 {290 if (hashBlock == 0)291 return 0;292 }293 else294 {295 CBlock blockTmp;296 if (pblock == NULL)297 {298 // Load the block this tx is in299 CTxIndex txindex;300 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))301 return 0;302 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, true))303 return 0;304 pblock = &blockTmp;305 }306307 // Update the tx's hashBlock308 hashBlock = pblock->GetHash();309310 // Locate the transaction311 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)312 if (pblock->vtx[nIndex] == *(CTransaction*)this)313 break;314 if (nIndex == pblock->vtx.size())315 {316 vMerkleBranch.clear();317 nIndex = -1;318 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");319 return 0;320 }321322 // Fill in merkle branch323 vMerkleBranch = pblock->GetMerkleBranch(nIndex);324 }325326 // Is the tx in a block that's in the main chain327 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);328 if (mi == mapBlockIndex.end())329 return 0;330 CBlockIndex* pindex = (*mi).second;331 if (!pindex || !pindex->IsInMainChain())332 return 0;333334 return pindexBest->nHeight - pindex->nHeight + 1;335}336337338339void CWalletTx::AddSupportingTransactions(CTxDB& txdb)340{341 vtxPrev.clear();342343 const int COPY_DEPTH = 3;344 if (SetMerkleBranch() < COPY_DEPTH)345 {346 vector<uint256> vWorkQueue;347 foreach(const CTxIn& txin, vin)348 vWorkQueue.push_back(txin.prevout.hash);349350 // This critsect is OK because txdb is already open351 CRITICAL_BLOCK(cs_mapWallet)352 {353 map<uint256, const CMerkleTx*> mapWalletPrev;354 set<uint256> setAlreadyDone;355 for (int i = 0; i < vWorkQueue.size(); i++)356 {357 uint256 hash = vWorkQueue[i];358 if (setAlreadyDone.count(hash))359 continue;360 setAlreadyDone.insert(hash);361362 CMerkleTx tx;363 if (mapWallet.count(hash))364 {365 tx = mapWallet[hash];366 foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)367 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;368 }369 else if (mapWalletPrev.count(hash))370 {371 tx = *mapWalletPrev[hash];372 }373 else if (!fClient && txdb.ReadDiskTx(hash, tx))374 {375 ;376 }377 else378 {379 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");380 continue;381 }382383 int nDepth = tx.SetMerkleBranch();384 vtxPrev.push_back(tx);385386 if (nDepth < COPY_DEPTH)387 foreach(const CTxIn& txin, tx.vin)388 vWorkQueue.push_back(txin.prevout.hash);389 }390 }391 }392393 reverse(vtxPrev.begin(), vtxPrev.end());394}395396397398399400401402403404405406bool CTransaction::AcceptTransaction(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)407{408 if (pfMissingInputs)409 *pfMissingInputs = false;410411 // Coinbase is only valid in a block, not as a loose transaction412 if (IsCoinBase())413 return error("AcceptTransaction() : coinbase as individual tx");414415 if (!CheckTransaction())416 return error("AcceptTransaction() : CheckTransaction failed");417418 // Do we already have it?419 uint256 hash = GetHash();420 CRITICAL_BLOCK(cs_mapTransactions)421 if (mapTransactions.count(hash))422 return false;423 if (fCheckInputs)424 if (txdb.ContainsTx(hash))425 return false;426427 // Check for conflicts with in-memory transactions428 CTransaction* ptxOld = NULL;429 for (int i = 0; i < vin.size(); i++)430 {431 COutPoint outpoint = vin[i].prevout;432 if (mapNextTx.count(outpoint))433 {434 // Allow replacing with a newer version of the same transaction435 if (i != 0)436 return false;437 ptxOld = mapNextTx[outpoint].ptx;438 if (!IsNewerThan(*ptxOld))439 return false;440 for (int i = 0; i < vin.size(); i++)441 {442 COutPoint outpoint = vin[i].prevout;443 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)444 return false;445 }446 break;447 }448 }449450 // Check against previous transactions451 map<uint256, CTxIndex> mapUnused;452 int64 nFees = 0;453 if (fCheckInputs && !ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), 0, nFees, false, false))454 {455 if (pfMissingInputs)456 *pfMissingInputs = true;457 return error("AcceptTransaction() : ConnectInputs failed %s", hash.ToString().substr(0,6).c_str());458 }459460 // Store transaction in memory461 CRITICAL_BLOCK(cs_mapTransactions)462 {463 if (ptxOld)464 {465 printf("mapTransaction.erase(%s) replacing with new version\n", ptxOld->GetHash().ToString().c_str());466 mapTransactions.erase(ptxOld->GetHash());467 }468 AddToMemoryPool();469 }470471 ///// are we sure this is ok when loading transactions or restoring block txes472 // If updated, erase old tx from wallet473 if (ptxOld)474 EraseFromWallet(ptxOld->GetHash());475476 printf("AcceptTransaction(): accepted %s\n", hash.ToString().substr(0,6).c_str());477 return true;478}479480481bool CTransaction::AddToMemoryPool()482{483 // Add to memory pool without checking anything. Don't call this directly,484 // call AcceptTransaction to properly check the transaction first.485 CRITICAL_BLOCK(cs_mapTransactions)486 {487 uint256 hash = GetHash();488 mapTransactions[hash] = *this;489 for (int i = 0; i < vin.size(); i++)490 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);491 nTransactionsUpdated++;492 }493 return true;494}495496497bool CTransaction::RemoveFromMemoryPool()498{499 // Remove transaction from memory pool500 CRITICAL_BLOCK(cs_mapTransactions)501 {502 foreach(const CTxIn& txin, vin)503 mapNextTx.erase(txin.prevout);504 mapTransactions.erase(GetHash());505 nTransactionsUpdated++;506 }507 return true;508}509510511512513514515int CMerkleTx::GetDepthInMainChain() const516{517 if (hashBlock == 0 || nIndex == -1)518 return 0;519520 // Find the block it claims to be in521 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);522 if (mi == mapBlockIndex.end())523 return 0;524 CBlockIndex* pindex = (*mi).second;525 if (!pindex || !pindex->IsInMainChain())526 return 0;527528 // Make sure the merkle branch connects to this block529 if (!fMerkleVerified)530 {531 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)532 return 0;533 fMerkleVerified = true;534 }535536 return pindexBest->nHeight - pindex->nHeight + 1;537}538539540int CMerkleTx::GetBlocksToMaturity() const541{542 if (!IsCoinBase())543 return 0;544 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());545}546547548bool CMerkleTx::AcceptTransaction(CTxDB& txdb, bool fCheckInputs)549{550 if (fClient)551 {552 if (!IsInMainChain() && !ClientConnectInputs())553 return false;554 return CTransaction::AcceptTransaction(txdb, false);555 }556 else557 {558 return CTransaction::AcceptTransaction(txdb, fCheckInputs);559 }560}561562563564bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)565{566 CRITICAL_BLOCK(cs_mapTransactions)567 {568 foreach(CMerkleTx& tx, vtxPrev)569 {570 if (!tx.IsCoinBase())571 {572 uint256 hash = tx.GetHash();573 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))574 tx.AcceptTransaction(txdb, fCheckInputs);575 }576 }577 if (!IsCoinBase())578 return AcceptTransaction(txdb, fCheckInputs);579 }580 return true;581}582583void ReacceptWalletTransactions()584{585 // Reaccept any txes of ours that aren't already in a block586 CTxDB txdb("r");587 CRITICAL_BLOCK(cs_mapWallet)588 {589 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)590 {591 CWalletTx& wtx = item.second;592 if (!wtx.IsCoinBase() && !txdb.ContainsTx(wtx.GetHash()))593 wtx.AcceptWalletTransaction(txdb, false);594 }595 }596}597598599void CWalletTx::RelayWalletTransaction(CTxDB& txdb)600{601 foreach(const CMerkleTx& tx, vtxPrev)602 {603 if (!tx.IsCoinBase())604 {605 uint256 hash = tx.GetHash();606 if (!txdb.ContainsTx(hash))607 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);608 }609 }610 if (!IsCoinBase())611 {612 uint256 hash = GetHash();613 if (!txdb.ContainsTx(hash))614 {615 printf("Relaying wtx %s\n", hash.ToString().substr(0,6).c_str());616 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);617 }618 }619}620621void RelayWalletTransactions()622{623 static int64 nLastTime;624 if (GetTime() - nLastTime < 10 * 60)625 return;626 nLastTime = GetTime();627628 // Rebroadcast any of our txes that aren't in a block yet629 printf("RelayWalletTransactions()\n");630 CTxDB txdb("r");631 CRITICAL_BLOCK(cs_mapWallet)632 {633 // Sort them in chronological order634 multimap<unsigned int, CWalletTx*> mapSorted;635 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)636 {637 CWalletTx& wtx = item.second;638 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));639 }640 foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)641 {642 CWalletTx& wtx = *item.second;643 wtx.RelayWalletTransaction(txdb);644 }645 }646}647648649650651652653654655656657//////////////////////////////////////////////////////////////////////////////658//659// CBlock and CBlockIndex660//661662bool CBlock::ReadFromDisk(const CBlockIndex* pblockindex, bool fReadTransactions)663{664 return ReadFromDisk(pblockindex->nFile, pblockindex->nBlockPos, fReadTransactions);665}666667uint256 GetOrphanRoot(const CBlock* pblock)668{669 // Work back to the first block in the orphan chain670 while (mapOrphanBlocks.count(pblock->hashPrevBlock))671 pblock = mapOrphanBlocks[pblock->hashPrevBlock];672 return pblock->GetHash();673}674675int64 CBlock::GetBlockValue(int64 nFees) const676{677 int64 nSubsidy = 50 * COIN;678679 // Subsidy is cut in half every 4 years680 nSubsidy >>= (nBestHeight / 210000);681682 return nSubsidy + nFees;683}684685unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)686{687 const unsigned int nTargetTimespan = 14 * 24 * 60 * 60; // two weeks688 const unsigned int nTargetSpacing = 10 * 60;689 const unsigned int nInterval = nTargetTimespan / nTargetSpacing;690691 // Genesis block692 if (pindexLast == NULL)693 return bnProofOfWorkLimit.GetCompact();694695 // Only change once per interval696 if ((pindexLast->nHeight+1) % nInterval != 0)697 return pindexLast->nBits;698699 // Go back by what we want to be 14 days worth of blocks700 const CBlockIndex* pindexFirst = pindexLast;701 for (int i = 0; pindexFirst && i < nInterval-1; i++)702 pindexFirst = pindexFirst->pprev;703 assert(pindexFirst);704705 // Limit adjustment step706 unsigned int nActualTimespan = pindexLast->nTime - pindexFirst->nTime;707 printf(" nActualTimespan = %d before bounds\n", nActualTimespan);708 if (nActualTimespan < nTargetTimespan/4)709 nActualTimespan = nTargetTimespan/4;710 if (nActualTimespan > nTargetTimespan*4)711 nActualTimespan = nTargetTimespan*4;712713 // Retarget714 CBigNum bnNew;715 bnNew.SetCompact(pindexLast->nBits);716 bnNew *= nActualTimespan;717 bnNew /= nTargetTimespan;718719 if (bnNew > bnProofOfWorkLimit)720 bnNew = bnProofOfWorkLimit;721722 /// debug print723 printf("\n\n\nGetNextWorkRequired RETARGET *****\n");724 printf("nTargetTimespan = %d nActualTimespan = %d\n", nTargetTimespan, nActualTimespan);725 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());726 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());727728 return bnNew.GetCompact();729}730731732733734735736737738739bool CTransaction::DisconnectInputs(CTxDB& txdb)740{741 // Relinquish previous transactions' spent pointers742 if (!IsCoinBase())743 {744 foreach(const CTxIn& txin, vin)745 {746 COutPoint prevout = txin.prevout;747748 // Get prev txindex from disk749 CTxIndex txindex;750 if (!txdb.ReadTxIndex(prevout.hash, txindex))751 return error("DisconnectInputs() : ReadTxIndex failed");752753 if (prevout.n >= txindex.vSpent.size())754 return error("DisconnectInputs() : prevout.n out of range");755756 // Mark outpoint as not spent757 txindex.vSpent[prevout.n].SetNull();758759 // Write back760 txdb.UpdateTxIndex(prevout.hash, txindex);761 }762 }763764 // Remove transaction from index765 if (!txdb.EraseTxIndex(*this))766 return error("DisconnectInputs() : EraseTxPos failed");767768 return true;769}770771772bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)773{774 // Take over previous transactions' spent pointers775 if (!IsCoinBase())776 {777 int64 nValueIn = 0;778 for (int i = 0; i < vin.size(); i++)779 {780 COutPoint prevout = vin[i].prevout;781782 // Read txindex783 CTxIndex txindex;784 bool fFound = true;785 if (fMiner && mapTestPool.count(prevout.hash))786 {787 // Get txindex from current proposed changes788 txindex = mapTestPool[prevout.hash];789 }790 else791 {792 // Read txindex from txdb793 fFound = txdb.ReadTxIndex(prevout.hash, txindex);794 }795 if (!fFound && (fBlock || fMiner))796 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());797798 // Read txPrev799 CTransaction txPrev;800 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))801 {802 // Get prev tx from single transactions in memory803 CRITICAL_BLOCK(cs_mapTransactions)804 {805 if (!mapTransactions.count(prevout.hash))806 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());807 txPrev = mapTransactions[prevout.hash];808 }809 if (!fFound)810 txindex.vSpent.resize(txPrev.vout.size());811 }812 else813 {814 // Get prev tx from disk815 if (!txPrev.ReadFromDisk(txindex.pos))816 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());817 }818819 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())820 return error("ConnectInputs() : %s prevout.n out of range %d %d %d", GetHash().ToString().substr(0,6).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size());821822 // If prev is coinbase, check that it's matured823 if (txPrev.IsCoinBase())824 for (CBlockIndex* pindex = pindexBest; pindex && nBestHeight - pindex->nHeight < COINBASE_MATURITY-1; pindex = pindex->pprev)825 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)826 return error("ConnectInputs() : tried to spend coinbase at depth %d", nBestHeight - pindex->nHeight);827828 // Verify signature829 if (!VerifySignature(txPrev, *this, i))830 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,6).c_str());831832 // Check for conflicts833 if (!txindex.vSpent[prevout.n].IsNull())834 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());835836 // Mark outpoints as spent837 txindex.vSpent[prevout.n] = posThisTx;838839 // Write back840 if (fBlock)841 txdb.UpdateTxIndex(prevout.hash, txindex);842 else if (fMiner)843 mapTestPool[prevout.hash] = txindex;844845 nValueIn += txPrev.vout[prevout.n].nValue;846 }847848 // Tally transaction fees849 int64 nTxFee = nValueIn - GetValueOut();850 if (nTxFee < 0)851 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,6).c_str());852 if (nTxFee < nMinFee)853 return false;854 nFees += nTxFee;855 }856857 if (fBlock)858 {859 // Add transaction to disk index860 if (!txdb.AddTxIndex(*this, posThisTx, nHeight))861 return error("ConnectInputs() : AddTxPos failed");862 }863 else if (fMiner)864 {865 // Add transaction to test pool866 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());867 }868869 return true;870}871872873bool CTransaction::ClientConnectInputs()874{875 if (IsCoinBase())876 return false;877878 // Take over previous transactions' spent pointers879 CRITICAL_BLOCK(cs_mapTransactions)880 {881 int64 nValueIn = 0;882 for (int i = 0; i < vin.size(); i++)883 {884 // Get prev tx from single transactions in memory885 COutPoint prevout = vin[i].prevout;886 if (!mapTransactions.count(prevout.hash))887 return false;888 CTransaction& txPrev = mapTransactions[prevout.hash];889890 if (prevout.n >= txPrev.vout.size())891 return false;892893 // Verify signature894 if (!VerifySignature(txPrev, *this, i))895 return error("ConnectInputs() : VerifySignature failed");896897 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of898 ///// this has to go away now that posNext is gone899 // // Check for conflicts900 // if (!txPrev.vout[prevout.n].posNext.IsNull())901 // return error("ConnectInputs() : prev tx already used");902 //903 // // Flag outpoints as used904 // txPrev.vout[prevout.n].posNext = posThisTx;905906 nValueIn += txPrev.vout[prevout.n].nValue;907 }908 if (GetValueOut() > nValueIn)909 return false;910 }911912 return true;913}914915916917918bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)919{920 // Disconnect in reverse order921 for (int i = vtx.size()-1; i >= 0; i--)922 if (!vtx[i].DisconnectInputs(txdb))923 return false;924925 // Update block index on disk without changing it in memory.926 // The memory index structure will be changed after the db commits.927 if (pindex->pprev)928 {929 CDiskBlockIndex blockindexPrev(pindex->pprev);930 blockindexPrev.hashNext = 0;931 txdb.WriteBlockIndex(blockindexPrev);932 }933934 return true;935}936937bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)938{939 //// issue here: it doesn't know the version940 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());941942 map<uint256, CTxIndex> mapUnused;943 int64 nFees = 0;944 foreach(CTransaction& tx, vtx)945 {946 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);947 nTxPos += ::GetSerializeSize(tx, SER_DISK);948949 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex->nHeight, nFees, true, false))950 return false;951 }952953 if (vtx[0].GetValueOut() > GetBlockValue(nFees))954 return false;955956 // Update block index on disk without changing it in memory.957 // The memory index structure will be changed after the db commits.958 if (pindex->pprev)959 {960 CDiskBlockIndex blockindexPrev(pindex->pprev);961 blockindexPrev.hashNext = pindex->GetBlockHash();962 txdb.WriteBlockIndex(blockindexPrev);963 }964965 // Watch for transactions paying to me966 foreach(CTransaction& tx, vtx)967 AddToWalletIfMine(tx, this);968969 return true;970}971972973974bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)975{976 printf("*** REORGANIZE ***\n");977978 // Find the fork979 CBlockIndex* pfork = pindexBest;980 CBlockIndex* plonger = pindexNew;981 while (pfork != plonger)982 {983 if (!(pfork = pfork->pprev))984 return error("Reorganize() : pfork->pprev is null");985 while (plonger->nHeight > pfork->nHeight)986 if (!(plonger = plonger->pprev))987 return error("Reorganize() : plonger->pprev is null");988 }989990 // List of what to disconnect991 vector<CBlockIndex*> vDisconnect;992 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)993 vDisconnect.push_back(pindex);994995 // List of what to connect996 vector<CBlockIndex*> vConnect;997 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)998 vConnect.push_back(pindex);999 reverse(vConnect.begin(), vConnect.end());10001001 // Disconnect shorter branch1002 vector<CTransaction> vResurrect;1003 foreach(CBlockIndex* pindex, vDisconnect)1004 {1005 CBlock block;1006 if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos, true))1007 return error("Reorganize() : ReadFromDisk for disconnect failed");1008 if (!block.DisconnectBlock(txdb, pindex))1009 return error("Reorganize() : DisconnectBlock failed");10101011 // Queue memory transactions to resurrect1012 foreach(const CTransaction& tx, block.vtx)1013 if (!tx.IsCoinBase())1014 vResurrect.push_back(tx);1015 }10161017 // Connect longer branch1018 vector<CTransaction> vDelete;1019 for (int i = 0; i < vConnect.size(); i++)1020 {1021 CBlockIndex* pindex = vConnect[i];1022 CBlock block;1023 if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos, true))1024 return error("Reorganize() : ReadFromDisk for connect failed");1025 if (!block.ConnectBlock(txdb, pindex))1026 {1027 // Invalid block, delete the rest of this branch1028 txdb.TxnAbort();1029 for (int j = i; j < vConnect.size(); j++)1030 {1031 CBlockIndex* pindex = vConnect[j];1032 pindex->EraseBlockFromDisk();1033 txdb.EraseBlockIndex(pindex->GetBlockHash());1034 mapBlockIndex.erase(pindex->GetBlockHash());1035 delete pindex;1036 }1037 return error("Reorganize() : ConnectBlock failed");1038 }10391040 // Queue memory transactions to delete1041 foreach(const CTransaction& tx, block.vtx)1042 vDelete.push_back(tx);1043 }1044 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))1045 return error("Reorganize() : WriteHashBestChain failed");10461047 // Commit now because resurrecting could take some time1048 txdb.TxnCommit();10491050 // Disconnect shorter branch1051 foreach(CBlockIndex* pindex, vDisconnect)1052 if (pindex->pprev)1053 pindex->pprev->pnext = NULL;10541055 // Connect longer branch1056 foreach(CBlockIndex* pindex, vConnect)1057 if (pindex->pprev)1058 pindex->pprev->pnext = pindex;10591060 // Resurrect memory transactions that were in the disconnected branch1061 foreach(CTransaction& tx, vResurrect)1062 tx.AcceptTransaction(txdb, false);10631064 // Delete redundant memory transactions that are in the connected branch1065 foreach(CTransaction& tx, vDelete)1066 tx.RemoveFromMemoryPool();10671068 return true;1069}107010711072bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)1073{1074 // Check for duplicate1075 uint256 hash = GetHash();1076 if (mapBlockIndex.count(hash))1077 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,14).c_str());10781079 // Construct new block index object1080 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);1081 if (!pindexNew)1082 return error("AddToBlockIndex() : new CBlockIndex failed");1083 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;1084 pindexNew->phashBlock = &((*mi).first);1085 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);1086 if (miPrev != mapBlockIndex.end())1087 {1088 pindexNew->pprev = (*miPrev).second;1089 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;1090 }10911092 CTxDB txdb;1093 txdb.TxnBegin();1094 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));10951096 // New best1097 if (pindexNew->nHeight > nBestHeight)1098 {1099 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)1100 {1101 pindexGenesisBlock = pindexNew;1102 txdb.WriteHashBestChain(hash);1103 }1104 else if (hashPrevBlock == hashBestChain)1105 {1106 // Adding to current best branch1107 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))1108 {1109 txdb.TxnAbort();1110 pindexNew->EraseBlockFromDisk();1111 mapBlockIndex.erase(pindexNew->GetBlockHash());1112 delete pindexNew;1113 return error("AddToBlockIndex() : ConnectBlock failed");1114 }1115 txdb.TxnCommit();1116 pindexNew->pprev->pnext = pindexNew;11171118 // Delete redundant memory transactions1119 foreach(CTransaction& tx, vtx)1120 tx.RemoveFromMemoryPool();1121 }1122 else1123 {1124 // New best branch1125 if (!Reorganize(txdb, pindexNew))1126 {1127 txdb.TxnAbort();1128 return error("AddToBlockIndex() : Reorganize failed");1129 }1130 }11311132 // New best link1133 hashBestChain = hash;1134 pindexBest = pindexNew;1135 nBestHeight = pindexBest->nHeight;1136 nTransactionsUpdated++;1137 printf("AddToBlockIndex: new best=%s height=%d\n", hashBestChain.ToString().substr(0,14).c_str(), nBestHeight);1138 }11391140 txdb.TxnCommit();1141 txdb.Close();11421143 // Relay wallet transactions that haven't gotten in yet1144 if (pindexNew == pindexBest)1145 RelayWalletTransactions();11461147 MainFrameRepaint();1148 return true;1149}11501151115211531154bool CBlock::CheckBlock() const1155{1156 // These are checks that are independent of context1157 // that can be verified before saving an orphan block.11581159 // Size limits1160 if (vtx.empty() || vtx.size() > MAX_SIZE || ::GetSerializeSize(*this, SER_DISK) > MAX_SIZE)1161 return error("CheckBlock() : size limits failed");11621163 // Check timestamp1164 if (nTime > GetAdjustedTime() + 2 * 60 * 60)1165 return error("CheckBlock() : block timestamp too far in the future");11661167 // First transaction must be coinbase, the rest must not be1168 if (vtx.empty() || !vtx[0].IsCoinBase())1169 return error("CheckBlock() : first tx is not coinbase");1170 for (int i = 1; i < vtx.size(); i++)1171 if (vtx[i].IsCoinBase())1172 return error("CheckBlock() : more than one coinbase");11731174 // Check transactions1175 foreach(const CTransaction& tx, vtx)1176 if (!tx.CheckTransaction())1177 return error("CheckBlock() : CheckTransaction failed");11781179 // Check proof of work matches claimed amount1180 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)1181 return error("CheckBlock() : nBits below minimum work");1182 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())1183 return error("CheckBlock() : hash doesn't match nBits");11841185 // Check merkleroot1186 if (hashMerkleRoot != BuildMerkleTree())1187 return error("CheckBlock() : hashMerkleRoot mismatch");11881189 return true;1190}11911192bool CBlock::AcceptBlock()1193{1194 // Check for duplicate1195 uint256 hash = GetHash();1196 if (mapBlockIndex.count(hash))1197 return error("AcceptBlock() : block already in mapBlockIndex");11981199 // Get prev block index1200 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);1201 if (mi == mapBlockIndex.end())1202 return error("AcceptBlock() : prev block not found");1203 CBlockIndex* pindexPrev = (*mi).second;12041205 // Check timestamp against prev1206 if (nTime <= pindexPrev->GetMedianTimePast())1207 return error("AcceptBlock() : block's timestamp is too early");12081209 // Check proof of work1210 if (nBits != GetNextWorkRequired(pindexPrev))1211 return error("AcceptBlock() : incorrect proof of work");12121213 // Write block to history file1214 unsigned int nFile;1215 unsigned int nBlockPos;1216 if (!WriteToDisk(!fClient, nFile, nBlockPos))1217 return error("AcceptBlock() : WriteToDisk failed");1218 if (!AddToBlockIndex(nFile, nBlockPos))1219 return error("AcceptBlock() : AddToBlockIndex failed");12201221 if (hashBestChain == hash)1222 RelayInventory(CInv(MSG_BLOCK, hash));12231224 // // Add atoms to user reviews for coins created1225 // vector<unsigned char> vchPubKey;1226 // if (ExtractPubKey(vtx[0].vout[0].scriptPubKey, false, vchPubKey))1227 // {1228 // unsigned short nAtom = GetRand(USHRT_MAX - 100) + 100;1229 // vector<unsigned short> vAtoms(1, nAtom);1230 // AddAtomsAndPropagate(Hash(vchPubKey.begin(), vchPubKey.end()), vAtoms, true);1231 // }12321233 return true;1234}12351236bool ProcessBlock(CNode* pfrom, CBlock* pblock)1237{1238 // Check for duplicate1239 uint256 hash = pblock->GetHash();1240 if (mapBlockIndex.count(hash))1241 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,14).c_str());1242 if (mapOrphanBlocks.count(hash))1243 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,14).c_str());12441245 // Preliminary checks1246 if (!pblock->CheckBlock())1247 {1248 delete pblock;1249 return error("ProcessBlock() : CheckBlock FAILED");1250 }12511252 // If don't already have its previous block, shunt it off to holding area until we get it1253 if (!mapBlockIndex.count(pblock->hashPrevBlock))1254 {1255 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,14).c_str());1256 mapOrphanBlocks.insert(make_pair(hash, pblock));1257 mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));12581259 // Ask this guy to fill in what we're missing1260 if (pfrom)1261 pfrom->PushMessage("getblocks", CBlockLocator(pindexBest), GetOrphanRoot(pblock));1262 return true;1263 }12641265 // Store to disk1266 if (!pblock->AcceptBlock())1267 {1268 delete pblock;1269 return error("ProcessBlock() : AcceptBlock FAILED");1270 }1271 delete pblock;12721273 // Recursively process any orphan blocks that depended on this one1274 vector<uint256> vWorkQueue;1275 vWorkQueue.push_back(hash);1276 for (int i = 0; i < vWorkQueue.size(); i++)1277 {1278 uint256 hashPrev = vWorkQueue[i];1279 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);1280 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);1281 ++mi)1282 {1283 CBlock* pblockOrphan = (*mi).second;1284 if (pblockOrphan->AcceptBlock())1285 vWorkQueue.push_back(pblockOrphan->GetHash());1286 mapOrphanBlocks.erase(pblockOrphan->GetHash());1287 delete pblockOrphan;1288 }1289 mapOrphanBlocksByPrev.erase(hashPrev);1290 }12911292 printf("ProcessBlock: ACCEPTED\n");1293 return true;1294}129512961297129812991300130113021303template<typename Stream>1304bool ScanMessageStart(Stream& s)1305{1306 // Scan ahead to the next pchMessageStart, which should normally be immediately1307 // at the file pointer. Leaves file pointer at end of pchMessageStart.1308 s.clear(0);1309 short prevmask = s.exceptions(0);1310 const char* p = BEGIN(pchMessageStart);1311 try1312 {1313 loop1314 {1315 char c;1316 s.read(&c, 1);1317 if (s.fail())1318 {1319 s.clear(0);1320 s.exceptions(prevmask);1321 return false;1322 }1323 if (*p != c)1324 p = BEGIN(pchMessageStart);1325 if (*p == c)1326 {1327 if (++p == END(pchMessageStart))1328 {1329 s.clear(0);1330 s.exceptions(prevmask);1331 return true;1332 }1333 }1334 }1335 }1336 catch (...)1337 {1338 s.clear(0);1339 s.exceptions(prevmask);1340 return false;1341 }1342}13431344string GetAppDir()1345{1346 string strDir;1347 if (!strSetDataDir.empty())1348 {1349 strDir = strSetDataDir;1350 }1351 else if (getenv("APPDATA"))1352 {1353 strDir = strprintf("%s\\Bitcoin", getenv("APPDATA"));1354 }1355 else if (getenv("USERPROFILE"))1356 {1357 string strAppData = strprintf("%s\\Application Data", getenv("USERPROFILE"));1358 static bool fMkdirDone;1359 if (!fMkdirDone)1360 {1361 fMkdirDone = true;1362 _mkdir(strAppData.c_str());1363 }1364 strDir = strprintf("%s\\Bitcoin", strAppData.c_str());1365 }1366 else1367 {1368 return ".";1369 }1370 static bool fMkdirDone;1371 if (!fMkdirDone)1372 {1373 fMkdirDone = true;1374 _mkdir(strDir.c_str());1375 }1376 return strDir;1377}13781379FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)1380{1381 if (nFile == -1)1382 return NULL;1383 FILE* file = fopen(strprintf("%s\\blk%04d.dat", GetAppDir().c_str(), nFile).c_str(), pszMode);1384 if (!file)1385 return NULL;1386 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))1387 {1388 if (fseek(file, nBlockPos, SEEK_SET) != 0)1389 {1390 fclose(file);1391 return NULL;1392 }1393 }1394 return file;1395}13961397static unsigned int nCurrentBlockFile = 1;13981399FILE* AppendBlockFile(unsigned int& nFileRet)1400{1401 nFileRet = 0;1402 loop1403 {1404 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");1405 if (!file)1406 return NULL;1407 if (fseek(file, 0, SEEK_END) != 0)1408 return NULL;1409 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB1410 if (ftell(file) < 0x7F000000 - MAX_SIZE)1411 {1412 nFileRet = nCurrentBlockFile;1413 return file;1414 }1415 fclose(file);1416 nCurrentBlockFile++;1417 }1418}14191420bool LoadBlockIndex(bool fAllowNew)1421{1422 //1423 // Load block index1424 //1425 CTxDB txdb("cr");1426 if (!txdb.LoadBlockIndex())1427 return false;1428 txdb.Close();14291430 //1431 // Init with genesis block1432 //1433 if (mapBlockIndex.empty())1434 {1435 if (!fAllowNew)1436 return false;143714381439 // Genesis Block:1440 // GetHash() = 0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f1441 // hashMerkleRoot = 0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b1442 // txNew.vin[0].scriptSig = 486604799 4 0x736B6E616220726F662074756F6C69616220646E6F63657320666F206B6E697262206E6F20726F6C6C65636E61684320393030322F6E614A2F33302073656D6954206568541443 // txNew.vout[0].nValue = 50000000001444 // txNew.vout[0].scriptPubKey = 0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704 OP_CHECKSIG1445 // block.nVersion = 11446 // block.nTime = 12310065051447 // block.nBits = 0x1d00ffff1448 // block.nNonce = 20832368931449 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)1450 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)1451 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)1452 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)1453 // vMerkleTree: 4a5e1e14541455 // Genesis block1456 char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";1457 CTransaction txNew;1458 txNew.vin.resize(1);1459 txNew.vout.resize(1);1460 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((unsigned char*)pszTimestamp, (unsigned char*)pszTimestamp + strlen(pszTimestamp));1461 txNew.vout[0].nValue = 50 * COIN;1462 txNew.vout[0].scriptPubKey = CScript() << CBigNum("0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704") << OP_CHECKSIG;1463 CBlock block;1464 block.vtx.push_back(txNew);1465 block.hashPrevBlock = 0;1466 block.hashMerkleRoot = block.BuildMerkleTree();1467 block.nVersion = 1;1468 block.nTime = 1231006505;1469 block.nBits = 0x1d00ffff;1470 block.nNonce = 2083236893;14711472 //// debug print, delete this later1473 printf("%s\n", block.GetHash().ToString().c_str());1474 printf("%s\n", block.hashMerkleRoot.ToString().c_str());1475 printf("%s\n", hashGenesisBlock.ToString().c_str());1476 txNew.vout[0].scriptPubKey.print();1477 block.print();1478 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));14791480 assert(block.GetHash() == hashGenesisBlock);14811482 // Start new block file1483 unsigned int nFile;1484 unsigned int nBlockPos;1485 if (!block.WriteToDisk(!fClient, nFile, nBlockPos))1486 return error("LoadBlockIndex() : writing genesis block to disk failed");1487 if (!block.AddToBlockIndex(nFile, nBlockPos))1488 return error("LoadBlockIndex() : genesis block not accepted");1489 }14901491 return true;1492}1493149414951496void PrintBlockTree()1497{1498 // precompute tree structure1499 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;1500 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)1501 {1502 CBlockIndex* pindex = (*mi).second;1503 mapNext[pindex->pprev].push_back(pindex);1504 // test1505 //while (rand() % 3 == 0)1506 // mapNext[pindex->pprev].push_back(pindex);1507 }15081509 vector<pair<int, CBlockIndex*> > vStack;1510 vStack.push_back(make_pair(0, pindexGenesisBlock));15111512 int nPrevCol = 0;1513 while (!vStack.empty())1514 {1515 int nCol = vStack.back().first;1516 CBlockIndex* pindex = vStack.back().second;1517 vStack.pop_back();15181519 // print split or gap1520 if (nCol > nPrevCol)1521 {1522 for (int i = 0; i < nCol-1; i++)1523 printf("| ");1524 printf("|\\\n");1525 }1526 else if (nCol < nPrevCol)1527 {1528 for (int i = 0; i < nCol; i++)1529 printf("| ");1530 printf("|\n");1531 }1532 nPrevCol = nCol;15331534 // print columns1535 for (int i = 0; i < nCol; i++)1536 printf("| ");15371538 // print item1539 CBlock block;1540 block.ReadFromDisk(pindex, true);1541 printf("%d (%u,%u) %s %s tx %d",1542 pindex->nHeight,1543 pindex->nFile,1544 pindex->nBlockPos,1545 block.GetHash().ToString().substr(0,14).c_str(),1546 DateTimeStr(block.nTime).c_str(),1547 block.vtx.size());15481549 CRITICAL_BLOCK(cs_mapWallet)1550 {1551 if (mapWallet.count(block.vtx[0].GetHash()))1552 {1553 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];1554 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());1555 }1556 }1557 printf("\n");155815591560 // put the main timechain first1561 vector<CBlockIndex*>& vNext = mapNext[pindex];1562 for (int i = 0; i < vNext.size(); i++)1563 {1564 if (vNext[i]->pnext)1565 {1566 swap(vNext[0], vNext[i]);1567 break;1568 }1569 }15701571 // iterate children1572 for (int i = 0; i < vNext.size(); i++)1573 vStack.push_back(make_pair(nCol+i, vNext[i]));1574 }1575}15761577157815791580158115821583158415851586//////////////////////////////////////////////////////////////////////////////1587//1588// Messages1589//159015911592bool AlreadyHave(CTxDB& txdb, const CInv& inv)1593{1594 switch (inv.type)1595 {1596 case MSG_TX: return mapTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);1597 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);1598 case MSG_REVIEW: return true;1599 case MSG_PRODUCT: return mapProducts.count(inv.hash);1600 }1601 // Don't know what it is, just say we already got one1602 return true;1603}16041605160616071608160916101611bool ProcessMessages(CNode* pfrom)1612{1613 CDataStream& vRecv = pfrom->vRecv;1614 if (vRecv.empty())1615 return true;1616 printf("ProcessMessages(%d bytes)\n", vRecv.size());16171618 //1619 // Message format1620 // (4) message start1621 // (12) command1622 // (4) size1623 // (x) data1624 //16251626 loop1627 {1628 // Scan for message start1629 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));1630 if (vRecv.end() - pstart < sizeof(CMessageHeader))1631 {1632 if (vRecv.size() > sizeof(CMessageHeader))1633 {1634 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");1635 vRecv.erase(vRecv.begin(), vRecv.end() - sizeof(CMessageHeader));1636 }1637 break;1638 }1639 if (pstart - vRecv.begin() > 0)1640 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());1641 vRecv.erase(vRecv.begin(), pstart);16421643 // Read header1644 CMessageHeader hdr;1645 vRecv >> hdr;1646 if (!hdr.IsValid())1647 {1648 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());1649 continue;1650 }1651 string strCommand = hdr.GetCommand();16521653 // Message size1654 unsigned int nMessageSize = hdr.nMessageSize;1655 if (nMessageSize > vRecv.size())1656 {1657 // Rewind and wait for rest of message1658 ///// need a mechanism to give up waiting for overlong message size error1659 printf("MESSAGE-BREAK 2\n");1660 vRecv.insert(vRecv.begin(), BEGIN(hdr), END(hdr));1661 Sleep(100);1662 break;1663 }16641665 // Copy message to its own buffer1666 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);1667 vRecv.ignore(nMessageSize);16681669 // Process message1670 bool fRet = false;1671 try1672 {1673 CheckForShutdown(2);1674 CRITICAL_BLOCK(cs_main)1675 fRet = ProcessMessage(pfrom, strCommand, vMsg);1676 CheckForShutdown(2);1677 }1678 CATCH_PRINT_EXCEPTION("ProcessMessage()")1679 if (!fRet)1680 printf("ProcessMessage(%s, %d bytes) from %s to %s FAILED\n", strCommand.c_str(), nMessageSize, pfrom->addr.ToString().c_str(), addrLocalHost.ToString().c_str());1681 }16821683 vRecv.Compact();1684 return true;1685}16861687168816891690bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)1691{1692 static map<unsigned int, vector<unsigned char> > mapReuseKey;1693 printf("received: %-12s (%d bytes) ", strCommand.c_str(), vRecv.size());1694 for (int i = 0; i < min(vRecv.size(), (unsigned int)25); i++)1695 printf("%02x ", vRecv[i] & 0xff);1696 printf("\n");1697 if (nDropMessagesTest > 0 && GetRand(nDropMessagesTest) == 0)1698 {1699 printf("dropmessages DROPPING RECV MESSAGE\n");1700 return true;1701 }1702170317041705 if (strCommand == "version")1706 {1707 // Can only do this once1708 if (pfrom->nVersion != 0)1709 return false;17101711 int64 nTime;1712 CAddress addrMe;1713 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;1714 if (pfrom->nVersion == 0)1715 return false;17161717 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));1718 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));17191720 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);1721 if (pfrom->fClient)1722 {1723 pfrom->vSend.nType |= SER_BLOCKHEADERONLY;1724 pfrom->vRecv.nType |= SER_BLOCKHEADERONLY;1725 }17261727 AddTimeData(pfrom->addr.ip, nTime);17281729 // Ask the first connected node for block updates1730 static bool fAskedForBlocks;1731 if (!fAskedForBlocks && !pfrom->fClient)1732 {1733 fAskedForBlocks = true;1734 pfrom->PushMessage("getblocks", CBlockLocator(pindexBest), uint256(0));1735 }17361737 printf("version message: %s has version %d, addrMe=%s\n", pfrom->addr.ToString().c_str(), pfrom->nVersion, addrMe.ToString().c_str());1738 }173917401741 else if (pfrom->nVersion == 0)1742 {1743 // Must have a version message before anything else1744 return false;1745 }174617471748 else if (strCommand == "addr")1749 {1750 vector<CAddress> vAddr;1751 vRecv >> vAddr;17521753 // Store the new addresses1754 CAddrDB addrdb;1755 foreach(const CAddress& addr, vAddr)1756 {1757 if (fShutdown)1758 return true;1759 if (AddAddress(addrdb, addr))1760 {1761 // Put on lists to send to other nodes1762 pfrom->setAddrKnown.insert(addr);1763 CRITICAL_BLOCK(cs_vNodes)1764 foreach(CNode* pnode, vNodes)1765 if (!pnode->setAddrKnown.count(addr))1766 pnode->vAddrToSend.push_back(addr);1767 }1768 }1769 }177017711772 else if (strCommand == "inv")1773 {1774 vector<CInv> vInv;1775 vRecv >> vInv;17761777 CTxDB txdb("r");1778 foreach(const CInv& inv, vInv)1779 {1780 if (fShutdown)1781 return true;1782 pfrom->AddInventoryKnown(inv);17831784 bool fAlreadyHave = AlreadyHave(txdb, inv);1785 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");17861787 if (!fAlreadyHave)1788 pfrom->AskFor(inv);1789 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))1790 pfrom->PushMessage("getblocks", CBlockLocator(pindexBest), GetOrphanRoot(mapOrphanBlocks[inv.hash]));1791 }1792 }179317941795 else if (strCommand == "getdata")1796 {1797 vector<CInv> vInv;1798 vRecv >> vInv;17991800 foreach(const CInv& inv, vInv)1801 {1802 if (fShutdown)1803 return true;1804 printf("received getdata for: %s\n", inv.ToString().c_str());18051806 if (inv.type == MSG_BLOCK)1807 {1808 // Send block from disk1809 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);1810 if (mi != mapBlockIndex.end())1811 {1812 //// could optimize this to send header straight from blockindex for client1813 CBlock block;1814 block.ReadFromDisk((*mi).second, !pfrom->fClient);1815 pfrom->PushMessage("block", block);1816 }1817 }1818 else if (inv.IsKnownType())1819 {1820 // Send stream from relay memory1821 CRITICAL_BLOCK(cs_mapRelay)1822 {1823 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);1824 if (mi != mapRelay.end())1825 pfrom->PushMessage(inv.GetCommand(), (*mi).second);1826 }1827 }1828 }1829 }183018311832 else if (strCommand == "getblocks")1833 {1834 CBlockLocator locator;1835 uint256 hashStop;1836 vRecv >> locator >> hashStop;18371838 // Find the first block the caller has in the main chain1839 CBlockIndex* pindex = locator.GetBlockIndex();18401841 // Send the rest of the chain1842 if (pindex)1843 pindex = pindex->pnext;1844 printf("getblocks %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,14).c_str());1845 for (; pindex; pindex = pindex->pnext)1846 {1847 if (pindex->GetBlockHash() == hashStop)1848 {1849 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,14).c_str());1850 break;1851 }18521853 // Bypass setInventoryKnown in case an inventory message got lost1854 CRITICAL_BLOCK(pfrom->cs_inventory)1855 {1856 CInv inv(MSG_BLOCK, pindex->GetBlockHash());1857 // returns true if wasn't already contained in the set1858 if (pfrom->setInventoryKnown2.insert(inv).second)1859 {1860 pfrom->setInventoryKnown.erase(inv);1861 pfrom->vInventoryToSend.push_back(inv);1862 }1863 }1864 }1865 }186618671868 else if (strCommand == "tx")1869 {1870 vector<uint256> vWorkQueue;1871 CDataStream vMsg(vRecv);1872 CTransaction tx;1873 vRecv >> tx;18741875 CInv inv(MSG_TX, tx.GetHash());1876 pfrom->AddInventoryKnown(inv);18771878 bool fMissingInputs = false;1879 if (tx.AcceptTransaction(true, &fMissingInputs))1880 {1881 AddToWalletIfMine(tx, NULL);1882 RelayMessage(inv, vMsg);1883 mapAlreadyAskedFor.erase(inv);1884 vWorkQueue.push_back(inv.hash);18851886 // Recursively process any orphan transactions that depended on this one1887 for (int i = 0; i < vWorkQueue.size(); i++)1888 {1889 uint256 hashPrev = vWorkQueue[i];1890 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);1891 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);1892 ++mi)1893 {1894 const CDataStream& vMsg = *((*mi).second);1895 CTransaction tx;1896 CDataStream(vMsg) >> tx;1897 CInv inv(MSG_TX, tx.GetHash());18981899 if (tx.AcceptTransaction(true))1900 {1901 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());1902 AddToWalletIfMine(tx, NULL);1903 RelayMessage(inv, vMsg);1904 mapAlreadyAskedFor.erase(inv);1905 vWorkQueue.push_back(inv.hash);1906 }1907 }1908 }19091910 foreach(uint256 hash, vWorkQueue)1911 EraseOrphanTx(hash);1912 }1913 else if (fMissingInputs)1914 {1915 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());1916 AddOrphanTx(vMsg);1917 }1918 }191919201921 else if (strCommand == "review")1922 {1923 CDataStream vMsg(vRecv);1924 CReview review;1925 vRecv >> review;19261927 CInv inv(MSG_REVIEW, review.GetHash());1928 pfrom->AddInventoryKnown(inv);19291930 if (review.AcceptReview())1931 {1932 // Relay the original message as-is in case it's a higher version than we know how to parse1933 RelayMessage(inv, vMsg);1934 mapAlreadyAskedFor.erase(inv);1935 }1936 }193719381939 else if (strCommand == "block")1940 {1941 auto_ptr<CBlock> pblock(new CBlock);1942 vRecv >> *pblock;19431944 //// debug print1945 printf("received block:\n"); pblock->print();19461947 CInv inv(MSG_BLOCK, pblock->GetHash());1948 pfrom->AddInventoryKnown(inv);19491950 if (ProcessBlock(pfrom, pblock.release()))1951 mapAlreadyAskedFor.erase(inv);1952 }195319541955 else if (strCommand == "getaddr")1956 {1957 pfrom->vAddrToSend.clear();1958 //// need to expand the time range if not enough found1959 int64 nSince = GetAdjustedTime() - 60 * 60; // in the last hour1960 CRITICAL_BLOCK(cs_mapAddresses)1961 {1962 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)1963 {1964 if (fShutdown)1965 return true;1966 const CAddress& addr = item.second;1967 if (addr.nTime > nSince)1968 pfrom->vAddrToSend.push_back(addr);1969 }1970 }1971 }197219731974 else if (strCommand == "checkorder")1975 {1976 uint256 hashReply;1977 CWalletTx order;1978 vRecv >> hashReply >> order;19791980 /// we have a chance to check the order here19811982 // Keep giving the same key to the same ip until they use it1983 if (!mapReuseKey.count(pfrom->addr.ip))1984 mapReuseKey[pfrom->addr.ip] = GenerateNewKey();19851986 // Send back approval of order and pubkey to use1987 CScript scriptPubKey;1988 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;1989 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);1990 }199119921993 else if (strCommand == "submitorder")1994 {1995 uint256 hashReply;1996 CWalletTx wtxNew;1997 vRecv >> hashReply >> wtxNew;19981999 // Broadcast2000 if (!wtxNew.AcceptWalletTransaction())2001 {2002 pfrom->PushMessage("reply", hashReply, (int)1);2003 return error("submitorder AcceptWalletTransaction() failed, returning error 1");2004 }2005 wtxNew.fTimeReceivedIsTxTime = true;2006 AddToWallet(wtxNew);2007 wtxNew.RelayWalletTransaction();2008 mapReuseKey.erase(pfrom->addr.ip);20092010 // Send back confirmation2011 pfrom->PushMessage("reply", hashReply, (int)0);2012 }201320142015 else if (strCommand == "reply")2016 {2017 uint256 hashReply;2018 vRecv >> hashReply;20192020 CRequestTracker tracker;2021 CRITICAL_BLOCK(pfrom->cs_mapRequests)2022 {2023 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);2024 if (mi != pfrom->mapRequests.end())2025 {2026 tracker = (*mi).second;2027 pfrom->mapRequests.erase(mi);2028 }2029 }2030 if (!tracker.IsNull())2031 tracker.fn(tracker.param1, vRecv);2032 }203320342035 else2036 {2037 // Ignore unknown commands for extensibility2038 printf("ProcessMessage(%s) : Ignored unknown message\n", strCommand.c_str());2039 }204020412042 if (!vRecv.empty())2043 printf("ProcessMessage(%s) : %d extra bytes\n", strCommand.c_str(), vRecv.size());20442045 return true;2046}2047204820492050205120522053205420552056bool SendMessages(CNode* pto)2057{2058 CheckForShutdown(2);2059 CRITICAL_BLOCK(cs_main)2060 {2061 // Don't send anything until we get their version message2062 if (pto->nVersion == 0)2063 return true;206420652066 //2067 // Message: addr2068 //2069 vector<CAddress> vAddrToSend;2070 vAddrToSend.reserve(pto->vAddrToSend.size());2071 foreach(const CAddress& addr, pto->vAddrToSend)2072 if (!pto->setAddrKnown.count(addr))2073 vAddrToSend.push_back(addr);2074 pto->vAddrToSend.clear();2075 if (!vAddrToSend.empty())2076 pto->PushMessage("addr", vAddrToSend);207720782079 //2080 // Message: inventory2081 //2082 vector<CInv> vInventoryToSend;2083 CRITICAL_BLOCK(pto->cs_inventory)2084 {2085 vInventoryToSend.reserve(pto->vInventoryToSend.size());2086 foreach(const CInv& inv, pto->vInventoryToSend)2087 {2088 // returns true if wasn't already contained in the set2089 if (pto->setInventoryKnown.insert(inv).second)2090 vInventoryToSend.push_back(inv);2091 }2092 pto->vInventoryToSend.clear();2093 pto->setInventoryKnown2.clear();2094 }2095 if (!vInventoryToSend.empty())2096 pto->PushMessage("inv", vInventoryToSend);209720982099 //2100 // Message: getdata2101 //2102 vector<CInv> vAskFor;2103 int64 nNow = GetTime() * 1000000;2104 CTxDB txdb("r");2105 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)2106 {2107 const CInv& inv = (*pto->mapAskFor.begin()).second;2108 printf("sending getdata: %s\n", inv.ToString().c_str());2109 if (!AlreadyHave(txdb, inv))2110 vAskFor.push_back(inv);2111 pto->mapAskFor.erase(pto->mapAskFor.begin());2112 }2113 if (!vAskFor.empty())2114 pto->PushMessage("getdata", vAskFor);21152116 }2117 return true;2118}211921202121212221232124212521262127212821292130213121322133//////////////////////////////////////////////////////////////////////////////2134//2135// BitcoinMiner2136//21372138int FormatHashBlocks(void* pbuffer, unsigned int len)2139{2140 unsigned char* pdata = (unsigned char*)pbuffer;2141 unsigned int blocks = 1 + ((len + 8) / 64);2142 unsigned char* pend = pdata + 64 * blocks;2143 memset(pdata + len, 0, 64 * blocks - len);2144 pdata[len] = 0x80;2145 unsigned int bits = len * 8;2146 pend[-1] = (bits >> 0) & 0xff;2147 pend[-2] = (bits >> 8) & 0xff;2148 pend[-3] = (bits >> 16) & 0xff;2149 pend[-4] = (bits >> 24) & 0xff;2150 return blocks;2151}21522153using CryptoPP::ByteReverse;2154static int detectlittleendian = 1;21552156void BlockSHA256(const void* pin, unsigned int nBlocks, void* pout)2157{2158 unsigned int* pinput = (unsigned int*)pin;2159 unsigned int* pstate = (unsigned int*)pout;21602161 CryptoPP::SHA256::InitState(pstate);21622163 if (*(char*)&detectlittleendian != 0)2164 {2165 for (int n = 0; n < nBlocks; n++)2166 {2167 unsigned int pbuf[16];2168 for (int i = 0; i < 16; i++)2169 pbuf[i] = ByteReverse(pinput[n * 16 + i]);2170 CryptoPP::SHA256::Transform(pstate, pbuf);2171 }2172 for (int i = 0; i < 8; i++)2173 pstate[i] = ByteReverse(pstate[i]);2174 }2175 else2176 {2177 for (int n = 0; n < nBlocks; n++)2178 CryptoPP::SHA256::Transform(pstate, pinput + n * 16);2179 }2180}218121822183bool BitcoinMiner()2184{2185 printf("BitcoinMiner started\n");2186 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);21872188 CKey key;2189 key.MakeNewKey();2190 CBigNum bnExtraNonce = 0;2191 while (fGenerateBitcoins)2192 {2193 Sleep(50);2194 CheckForShutdown(3);2195 while (vNodes.empty())2196 {2197 Sleep(1000);2198 CheckForShutdown(3);2199 }22002201 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;2202 CBlockIndex* pindexPrev = pindexBest;2203 unsigned int nBits = GetNextWorkRequired(pindexPrev);220422052206 //2207 // Create coinbase tx2208 //2209 CTransaction txNew;2210 txNew.vin.resize(1);2211 txNew.vin[0].prevout.SetNull();2212 txNew.vin[0].scriptSig << nBits << ++bnExtraNonce;2213 txNew.vout.resize(1);2214 txNew.vout[0].scriptPubKey << key.GetPubKey() << OP_CHECKSIG;221522162217 //2218 // Create new block2219 //2220 auto_ptr<CBlock> pblock(new CBlock());2221 if (!pblock.get())2222 return false;22232224 // Add our coinbase tx as first transaction2225 pblock->vtx.push_back(txNew);22262227 // Collect the latest transactions into the block2228 int64 nFees = 0;2229 CRITICAL_BLOCK(cs_main)2230 CRITICAL_BLOCK(cs_mapTransactions)2231 {2232 CTxDB txdb("r");2233 map<uint256, CTxIndex> mapTestPool;2234 vector<char> vfAlreadyAdded(mapTransactions.size());2235 bool fFoundSomething = true;2236 unsigned int nBlockSize = 0;2237 while (fFoundSomething && nBlockSize < MAX_SIZE/2)2238 {2239 fFoundSomething = false;2240 unsigned int n = 0;2241 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi, ++n)2242 {2243 if (vfAlreadyAdded[n])2244 continue;2245 CTransaction& tx = (*mi).second;2246 if (tx.IsCoinBase() || !tx.IsFinal())2247 continue;22482249 // Transaction fee requirements, mainly only needed for flood control2250 // Under 10K (about 80 inputs) is free for first 100 transactions2251 // Base rate is 0.01 per KB2252 int64 nMinFee = tx.GetMinFee(pblock->vtx.size() < 100);22532254 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);2255 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), 0, nFees, false, true, nMinFee))2256 continue;2257 swap(mapTestPool, mapTestPoolTmp);22582259 pblock->vtx.push_back(tx);2260 nBlockSize += ::GetSerializeSize(tx, SER_NETWORK);2261 vfAlreadyAdded[n] = true;2262 fFoundSomething = true;2263 }2264 }2265 }2266 pblock->nBits = nBits;2267 pblock->vtx[0].vout[0].nValue = pblock->GetBlockValue(nFees);2268 printf("\n\nRunning BitcoinMiner with %d transactions in block\n", pblock->vtx.size());226922702271 //2272 // Prebuild hash buffer2273 //2274 struct unnamed12275 {2276 struct unnamed22277 {2278 int nVersion;2279 uint256 hashPrevBlock;2280 uint256 hashMerkleRoot;2281 unsigned int nTime;2282 unsigned int nBits;2283 unsigned int nNonce;2284 }2285 block;2286 unsigned char pchPadding0[64];2287 uint256 hash1;2288 unsigned char pchPadding1[64];2289 }2290 tmp;22912292 tmp.block.nVersion = pblock->nVersion;2293 tmp.block.hashPrevBlock = pblock->hashPrevBlock = (pindexPrev ? pindexPrev->GetBlockHash() : 0);2294 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();2295 tmp.block.nTime = pblock->nTime = max((pindexPrev ? pindexPrev->GetMedianTimePast()+1 : 0), GetAdjustedTime());2296 tmp.block.nBits = pblock->nBits = nBits;2297 tmp.block.nNonce = pblock->nNonce = 1;22982299 unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));2300 unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));230123022303 //2304 // Search2305 //2306 unsigned int nStart = GetTime();2307 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();2308 uint256 hash;2309 loop2310 {2311 BlockSHA256(&tmp.block, nBlocks0, &tmp.hash1);2312 BlockSHA256(&tmp.hash1, nBlocks1, &hash);231323142315 if (hash <= hashTarget)2316 {2317 pblock->nNonce = tmp.block.nNonce;2318 assert(hash == pblock->GetHash());23192320 //// debug print2321 printf("BitcoinMiner:\n");2322 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());2323 pblock->print();23242325 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);2326 CRITICAL_BLOCK(cs_main)2327 {2328 // Save key2329 if (!AddKey(key))2330 return false;2331 key.MakeNewKey();23322333 // Process this block the same as if we had received it from another node2334 if (!ProcessBlock(NULL, pblock.release()))2335 printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");2336 }2337 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);23382339 Sleep(500);2340 break;2341 }23422343 // Update nTime every few seconds2344 if ((++tmp.block.nNonce & 0x3ffff) == 0)2345 {2346 CheckForShutdown(3);2347 if (tmp.block.nNonce == 0)2348 break;2349 if (pindexPrev != pindexBest)2350 break;2351 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)2352 break;2353 if (!fGenerateBitcoins)2354 break;2355 tmp.block.nTime = pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());2356 }2357 }2358 }23592360 return true;2361}2362236323642365236623672368236923702371237223732374237523762377237823792380//////////////////////////////////////////////////////////////////////////////2381//2382// Actions2383//238423852386int64 GetBalance()2387{2388 int64 nStart, nEnd;2389 QueryPerformanceCounter((LARGE_INTEGER*)&nStart);23902391 int64 nTotal = 0;2392 CRITICAL_BLOCK(cs_mapWallet)2393 {2394 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)2395 {2396 CWalletTx* pcoin = &(*it).second;2397 if (!pcoin->IsFinal() || pcoin->fSpent)2398 continue;2399 nTotal += pcoin->GetCredit();2400 }2401 }24022403 QueryPerformanceCounter((LARGE_INTEGER*)&nEnd);2404 ///printf(" GetBalance() time = %16I64d\n", nEnd - nStart);2405 return nTotal;2406}2407240824092410bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)2411{2412 setCoinsRet.clear();24132414 // List of values less than target2415 int64 nLowestLarger = _I64_MAX;2416 CWalletTx* pcoinLowestLarger = NULL;2417 vector<pair<int64, CWalletTx*> > vValue;2418 int64 nTotalLower = 0;24192420 CRITICAL_BLOCK(cs_mapWallet)2421 {2422 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)2423 {2424 CWalletTx* pcoin = &(*it).second;2425 if (!pcoin->IsFinal() || pcoin->fSpent)2426 continue;2427 int64 n = pcoin->GetCredit();2428 if (n <= 0)2429 continue;2430 if (n < nTargetValue)2431 {2432 vValue.push_back(make_pair(n, pcoin));2433 nTotalLower += n;2434 }2435 else if (n == nTargetValue)2436 {2437 setCoinsRet.insert(pcoin);2438 return true;2439 }2440 else if (n < nLowestLarger)2441 {2442 nLowestLarger = n;2443 pcoinLowestLarger = pcoin;2444 }2445 }2446 }24472448 if (nTotalLower < nTargetValue)2449 {2450 if (pcoinLowestLarger == NULL)2451 return false;2452 setCoinsRet.insert(pcoinLowestLarger);2453 return true;2454 }24552456 // Solve subset sum by stochastic approximation2457 sort(vValue.rbegin(), vValue.rend());2458 vector<char> vfIncluded;2459 vector<char> vfBest(vValue.size(), true);2460 int64 nBest = nTotalLower;24612462 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)2463 {2464 vfIncluded.assign(vValue.size(), false);2465 int64 nTotal = 0;2466 bool fReachedTarget = false;2467 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)2468 {2469 for (int i = 0; i < vValue.size(); i++)2470 {2471 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])2472 {2473 nTotal += vValue[i].first;2474 vfIncluded[i] = true;2475 if (nTotal >= nTargetValue)2476 {2477 fReachedTarget = true;2478 if (nTotal < nBest)2479 {2480 nBest = nTotal;2481 vfBest = vfIncluded;2482 }2483 nTotal -= vValue[i].first;2484 vfIncluded[i] = false;2485 }2486 }2487 }2488 }2489 }24902491 // If the next larger is still closer, return it2492 if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)2493 setCoinsRet.insert(pcoinLowestLarger);2494 else2495 {2496 for (int i = 0; i < vValue.size(); i++)2497 if (vfBest[i])2498 setCoinsRet.insert(vValue[i].second);24992500 //// debug print2501 printf("SelectCoins() best subset: ");2502 for (int i = 0; i < vValue.size(); i++)2503 if (vfBest[i])2504 printf("%s ", FormatMoney(vValue[i].first).c_str());2505 printf("total %s\n", FormatMoney(nBest).c_str());2506 }25072508 return true;2509}25102511251225132514bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, int64& nFeeRequiredRet)2515{2516 nFeeRequiredRet = 0;2517 CRITICAL_BLOCK(cs_main)2518 {2519 // txdb must be opened before the mapWallet lock2520 CTxDB txdb("r");2521 CRITICAL_BLOCK(cs_mapWallet)2522 {2523 int64 nFee = nTransactionFee;2524 loop2525 {2526 wtxNew.vin.clear();2527 wtxNew.vout.clear();2528 if (nValue < 0)2529 return false;2530 int64 nValueOut = nValue;2531 nValue += nFee;25322533 // Choose coins to use2534 set<CWalletTx*> setCoins;2535 if (!SelectCoins(nValue, setCoins))2536 return false;2537 int64 nValueIn = 0;2538 foreach(CWalletTx* pcoin, setCoins)2539 nValueIn += pcoin->GetCredit();25402541 // Fill vout[0] to the payee2542 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));25432544 // Fill vout[1] back to self with any change2545 if (nValueIn > nValue)2546 {2547 // Use the same key as one of the coins2548 vector<unsigned char> vchPubKey;2549 CTransaction& txFirst = *(*setCoins.begin());2550 foreach(const CTxOut& txout, txFirst.vout)2551 if (txout.IsMine())2552 if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))2553 break;2554 if (vchPubKey.empty())2555 return false;25562557 // Fill vout[1] to ourself2558 CScript scriptPubKey;2559 scriptPubKey << vchPubKey << OP_CHECKSIG;2560 wtxNew.vout.push_back(CTxOut(nValueIn - nValue, scriptPubKey));2561 }25622563 // Fill vin2564 foreach(CWalletTx* pcoin, setCoins)2565 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)2566 if (pcoin->vout[nOut].IsMine())2567 wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));25682569 // Sign2570 int nIn = 0;2571 foreach(CWalletTx* pcoin, setCoins)2572 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)2573 if (pcoin->vout[nOut].IsMine())2574 SignSignature(*pcoin, wtxNew, nIn++);25752576 // Check that enough fee is included2577 if (nFee < wtxNew.GetMinFee(true))2578 {2579 nFee = nFeeRequiredRet = wtxNew.GetMinFee(true);2580 continue;2581 }25822583 // Fill vtxPrev by copying from previous transactions vtxPrev2584 wtxNew.AddSupportingTransactions(txdb);2585 wtxNew.fTimeReceivedIsTxTime = true;25862587 break;2588 }2589 }2590 }2591 return true;2592}25932594// Call after CreateTransaction unless you want to abort2595bool CommitTransactionSpent(const CWalletTx& wtxNew)2596{2597 CRITICAL_BLOCK(cs_main)2598 CRITICAL_BLOCK(cs_mapWallet)2599 {2600 //// todo: make this transactional, never want to add a transaction2601 //// without marking spent transactions26022603 // Add tx to wallet, because if it has change it's also ours,2604 // otherwise just for transaction history.2605 AddToWallet(wtxNew);26062607 // Mark old coins as spent2608 set<CWalletTx*> setCoins;2609 foreach(const CTxIn& txin, wtxNew.vin)2610 setCoins.insert(&mapWallet[txin.prevout.hash]);2611 foreach(CWalletTx* pcoin, setCoins)2612 {2613 pcoin->fSpent = true;2614 pcoin->WriteToDisk();2615 vWalletUpdated.push_back(make_pair(pcoin->GetHash(), false));2616 }2617 }2618 MainFrameRepaint();2619 return true;2620}26212622262326242625bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew)2626{2627 CRITICAL_BLOCK(cs_main)2628 {2629 int64 nFeeRequired;2630 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, nFeeRequired))2631 {2632 string strError;2633 if (nValue + nFeeRequired > GetBalance())2634 strError = strprintf("Error: This is an oversized transaction that requires a transaction fee of %s ", FormatMoney(nFeeRequired).c_str());2635 else2636 strError = "Error: Transaction creation failed ";2637 wxMessageBox(strError, "Sending...");2638 return error("SendMoney() : %s\n", strError.c_str());2639 }2640 if (!CommitTransactionSpent(wtxNew))2641 {2642 wxMessageBox("Error finalizing transaction", "Sending...");2643 return error("SendMoney() : Error finalizing transaction");2644 }26452646 printf("SendMoney: %s\n", wtxNew.GetHash().ToString().substr(0,6).c_str());26472648 // Broadcast2649 if (!wtxNew.AcceptTransaction())2650 {2651 // This must not fail. The transaction has already been signed and recorded.2652 throw runtime_error("SendMoney() : wtxNew.AcceptTransaction() failed\n");2653 wxMessageBox("Error: Transaction not valid", "Sending...");2654 return error("SendMoney() : Error: Transaction not valid");2655 }2656 wtxNew.RelayWalletTransaction();2657 }2658 MainFrameRepaint();2659 return true;2660}
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
