Research
Timechain
Search Donate
Sponsors
Cake Wallet, private Bitcoin and Monero walletSideShift.ai, no-signup crypto exchangeOrangeRock, non-custodial bitcoin spot and perps tradingBraiins Hashpower, buy and sell Bitcoin hashrateeCash.com
What changed

Bitcoin v0.3.10 → v0.3.12

20 files · +1,251 · −577 · 8c9479c6b · 2010-09-07 · s_nakamoto

Release commit message: cleanup, catch some recoverable exceptions and continue -- version 0.3.12 release

Full source: v0.3.10. Previous diff: v0.3.8 → v0.3.10. Next: v0.3.12 → v0.3.13.

db.cpp (modified)

1--- v0.3.10/db.cpp2+++ v0.3.12/db.cpp3@@ -81,7 +81,7 @@4                              DB_RECOVER,5                              S_IRUSR | S_IWUSR);6             if (ret > 0)7-                throw runtime_error(strprintf("CDB() : error %d opening database environment\n", ret));8+                throw runtime_error(strprintf("CDB() : error %d opening database environment", ret));9             fDbEnvInit = true;10         }11 12@@ -106,7 +106,7 @@13                 CRITICAL_BLOCK(cs_db)14                     --mapFileUseCount[strFile];15                 strFile = "";16-                throw runtime_error(strprintf("CDB() : can't open database file %s, error %d\n", pszFile, ret));17+                throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));18             }19 20             if (fCreate && !Exists(string("version")))21@@ -419,6 +419,9 @@22             // Watch for genesis block23             if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)24                 pindexGenesisBlock = pindexNew;25+26+            if (!pindexNew->CheckIndex())27+                return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);28         }29         else30         {31@@ -454,10 +457,36 @@32     pindexBest = mapBlockIndex[hashBestChain];33     nBestHeight = pindexBest->nHeight;34     bnBestChainWork = pindexBest->bnChainWork;35-    printf("LoadBlockIndex(): hashBestChain=%s  height=%d\n", hashBestChain.ToString().substr(0,16).c_str(), nBestHeight);36+    printf("LoadBlockIndex(): hashBestChain=%s  height=%d\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight);37 38     // Load bnBestInvalidWork, OK if it doesn't exist39     ReadBestInvalidWork(bnBestInvalidWork);40+41+    // Verify blocks in the best chain42+    CBlockIndex* pindexFork = NULL;43+    for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)44+    {45+        if (pindex->nHeight < 74000 && !mapArgs.count("-checkblocks"))46+            break;47+        CBlock block;48+        if (!block.ReadFromDisk(pindex))49+            return error("LoadBlockIndex() : block.ReadFromDisk failed");50+        if (!block.CheckBlock())51+        {52+            printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());53+            pindexFork = pindex->pprev;54+        }55+    }56+    if (pindexFork)57+    {58+        // Reorg back to the fork59+        printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);60+        CBlock block;61+        if (!block.ReadFromDisk(pindexFork))62+            return error("LoadBlockIndex() : block.ReadFromDisk failed");63+        CTxDB txdb;64+        block.SetBestChain(txdb, pindexFork);65+    }66 67     return true;68 }69@@ -605,8 +634,8 @@70                 //printf("LoadWallet  %s\n", wtx.GetHash().ToString().c_str());71                 //printf(" %12I64d  %s  %s  %s\n",72                 //    wtx.vout[0].nValue,73-                //    DateTimeStrFormat("%x %H:%M:%S", wtx.nTime).c_str(),74-                //    wtx.hashBlock.ToString().substr(0,16).c_str(),75+                //    DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),76+                //    wtx.hashBlock.ToString().substr(0,20).c_str(),77                 //    wtx.mapValue["message"].c_str());78             }79             else if (strType == "key" || strType == "wkey")80@@ -775,3 +804,37 @@81     }82 }83 84+void BackupWallet(const string& strDest)85+{86+    while (!fShutdown)87+    {88+        CRITICAL_BLOCK(cs_db)89+        {90+            const string strFile = "wallet.dat";91+            if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)92+            {93+                // Flush log data to the dat file94+                CloseDb(strFile);95+                dbenv.txn_checkpoint(0, 0, 0);96+                dbenv.lsn_reset(strFile.c_str(), 0);97+                mapFileUseCount.erase(strFile);98+99+                // Copy wallet.dat100+                filesystem::path pathSrc(GetDataDir() + "/" + strFile);101+                filesystem::path pathDest(strDest);102+                if (filesystem::is_directory(pathDest))103+                    pathDest = pathDest / strFile;104+#if BOOST_VERSION >= 104000105+                filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);106+#else107+                filesystem::copy_file(pathSrc, pathDest);108+#endif109+                printf("copied wallet.dat to %s\n", pathDest.string().c_str());110+111+                return;112+            }113+        }114+        Sleep(100);115+    }116+}117+

db.h (modified)

1--- v0.3.10/db.h2+++ v0.3.12/db.h3@@ -399,6 +399,7 @@4 };5 6 bool LoadWallet(bool& fFirstRunRet);7+void BackupWallet(const string& strDest);8 9 inline bool SetAddressBookName(const string& strAddress, const string& strName)10 {

init.cpp (modified)

1--- v0.3.10/init.cpp2+++ v0.3.12/init.cpp3@@ -297,7 +297,7 @@4 5     if (!strErrors.empty())6     {7-        wxMessageBox(strErrors, "Bitcoin");8+        wxMessageBox(strErrors, "Bitcoin", wxOK | wxICON_ERROR);9         return false;10     }11 12@@ -374,7 +374,7 @@13             return false;14         }15         if (nTransactionFee > 1 * COIN)16-            wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin");17+            wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);18     }19 20     //

irc.cpp (modified)

1--- v0.3.10/irc.cpp2+++ v0.3.12/irc.cpp3@@ -5,6 +5,9 @@4 #include "headers.h"5 6 int nGotIRCAddresses = 0;7+8+void ThreadIRCSeed2(void* parg);9+10 11 12 13@@ -128,6 +131,7 @@14     loop15     {16         string strLine;17+        strLine.reserve(10000);18         if (!RecvLineIRC(hSocket, strLine))19             return 0;20         printf("IRC %s\n", strLine.c_str());21@@ -158,6 +162,21 @@22 23 void ThreadIRCSeed(void* parg)24 {25+    IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg));26+    try27+    {28+        ThreadIRCSeed2(parg);29+    }30+    catch (std::exception& e) {31+        PrintExceptionContinue(&e, "ThreadIRCSeed()");32+    } catch (...) {33+        PrintExceptionContinue(NULL, "ThreadIRCSeed()");34+    }35+    printf("ThreadIRCSeed exiting\n");36+}37+38+void ThreadIRCSeed2(void* parg)39+{40     if (mapArgs.count("-connect"))41         return;42     if (mapArgs.count("-noirc"))43@@ -236,6 +255,7 @@44 45         int64 nStart = GetTime();46         string strLine;47+        strLine.reserve(10000);48         while (!fShutdown && RecvLineIRC(hSocket, strLine))49         {50             if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')

main.cpp (modified)

1--- v0.3.10/main.cpp2+++ v0.3.12/main.cpp3@@ -91,7 +91,7 @@4     CKey key;5     key.MakeNewKey();6     if (!AddKey(key))7-        throw runtime_error("GenerateNewKey() : AddKey failed\n");8+        throw runtime_error("GenerateNewKey() : AddKey failed");9     return key.GetPubKey();10 }11 12@@ -487,21 +487,25 @@13 14 15 16-bool CTransaction::AcceptTransaction(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)17+bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)18 {19     if (pfMissingInputs)20         *pfMissingInputs = false;21 22     // Coinbase is only valid in a block, not as a loose transaction23     if (IsCoinBase())24-        return error("AcceptTransaction() : coinbase as individual tx");25+        return error("AcceptToMemoryPool() : coinbase as individual tx");26 27     if (!CheckTransaction())28-        return error("AcceptTransaction() : CheckTransaction failed");29+        return error("AcceptToMemoryPool() : CheckTransaction failed");30 31     // To help v0.1.5 clients who would see it as a negative number32-    if (nLockTime > INT_MAX)33-        return error("AcceptTransaction() : not accepting nLockTime beyond 2038");34+    if ((int64)nLockTime > INT_MAX)35+        return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");36+37+    // Rather not work on nonstandard transactions38+    if (GetSigOpCount() > 2 || ::GetSerializeSize(*this, SER_NETWORK) < 100)39+        return error("AcceptToMemoryPool() : nonstandard transaction");40 41     // Do we already have it?42     uint256 hash = GetHash();43@@ -519,6 +523,9 @@44         COutPoint outpoint = vin[i].prevout;45         if (mapNextTx.count(outpoint))46         {47+            // Disable replacement feature for now48+            return false;49+50             // Allow replacing with a newer version of the same transaction51             if (i != 0)52                 return false;53@@ -542,7 +549,7 @@54     {55         if (pfMissingInputs)56             *pfMissingInputs = true;57-        return error("AcceptTransaction() : ConnectInputs failed %s", hash.ToString().substr(0,6).c_str());58+        return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,6).c_str());59     }60 61     // Store transaction in memory62@@ -550,10 +557,10 @@63     {64         if (ptxOld)65         {66-            printf("mapTransaction.erase(%s) replacing with new version\n", ptxOld->GetHash().ToString().c_str());67-            mapTransactions.erase(ptxOld->GetHash());68-        }69-        AddToMemoryPool();70+            printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());71+            ptxOld->RemoveFromMemoryPool();72+        }73+        AddToMemoryPoolUnchecked();74     }75 76     ///// are we sure this is ok when loading transactions or restoring block txes77@@ -561,15 +568,15 @@78     if (ptxOld)79         EraseFromWallet(ptxOld->GetHash());80 81-    printf("AcceptTransaction(): accepted %s\n", hash.ToString().substr(0,6).c_str());82+    printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,6).c_str());83     return true;84 }85 86 87-bool CTransaction::AddToMemoryPool()88+bool CTransaction::AddToMemoryPoolUnchecked()89 {90     // Add to memory pool without checking anything.  Don't call this directly,91-    // call AcceptTransaction to properly check the transaction first.92+    // call AcceptToMemoryPool to properly check the transaction first.93     CRITICAL_BLOCK(cs_mapTransactions)94     {95         uint256 hash = GetHash();96@@ -634,17 +641,17 @@97 }98 99 100-bool CMerkleTx::AcceptTransaction(CTxDB& txdb, bool fCheckInputs)101+bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)102 {103     if (fClient)104     {105         if (!IsInMainChain() && !ClientConnectInputs())106             return false;107-        return CTransaction::AcceptTransaction(txdb, false);108+        return CTransaction::AcceptToMemoryPool(txdb, false);109     }110     else111     {112-        return CTransaction::AcceptTransaction(txdb, fCheckInputs);113+        return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);114     }115 }116 117@@ -654,19 +661,19 @@118 {119     CRITICAL_BLOCK(cs_mapTransactions)120     {121+        // Add previous supporting transactions first122         foreach(CMerkleTx& tx, vtxPrev)123         {124             if (!tx.IsCoinBase())125             {126                 uint256 hash = tx.GetHash();127                 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))128-                    tx.AcceptTransaction(txdb, fCheckInputs);129-            }130-        }131-        if (!IsCoinBase())132-            return AcceptTransaction(txdb, fCheckInputs);133-    }134-    return true;135+                    tx.AcceptToMemoryPool(txdb, fCheckInputs);136+            }137+        }138+        return AcceptToMemoryPool(txdb, fCheckInputs);139+    }140+    return false;141 }142 143 void ReacceptWalletTransactions()144@@ -748,6 +755,12 @@145     if (fFirst)146         return;147 148+    // Only do it if there's been a new block since last time149+    static int64 nLastTime;150+    if (nTimeBestReceived < nLastTime)151+        return;152+    nLastTime = GetTime();153+154     // Rebroadcast any of our txes that aren't in a block yet155     printf("ResendWalletTransactions()\n");156     CTxDB txdb("r");157@@ -785,9 +798,13 @@158 // CBlock and CBlockIndex159 //160 161-bool CBlock::ReadFromDisk(const CBlockIndex* pblockindex, bool fReadTransactions)162-{163-    return ReadFromDisk(pblockindex->nFile, pblockindex->nBlockPos, fReadTransactions);164+bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)165+{166+    if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))167+        return false;168+    if (GetHash() != pindex->GetBlockHash())169+        return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");170+    return true;171 }172 173 uint256 GetOrphanRoot(const CBlock* pblock)174@@ -829,7 +846,7 @@175     assert(pindexFirst);176 177     // Limit adjustment step178-    int64 nActualTimespan = (int64)pindexLast->nTime - (int64)pindexFirst->nTime;179+    int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();180     printf("  nActualTimespan = %"PRI64d"  before bounds\n", nActualTimespan);181     if (nActualTimespan < nTargetTimespan/4)182         nActualTimespan = nTargetTimespan/4;183@@ -854,6 +871,22 @@184     return bnNew.GetCompact();185 }186 187+bool CheckProofOfWork(uint256 hash, unsigned int nBits)188+{189+    CBigNum bnTarget;190+    bnTarget.SetCompact(nBits);191+192+    // Check range193+    if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)194+        return error("CheckProofOfWork() : nBits below minimum work");195+196+    // Check proof of work matches claimed amount197+    if (hash > bnTarget.getuint256())198+        return error("CheckProofOfWork() : hash doesn't match nBits");199+200+    return true;201+}202+203 bool IsInitialBlockDownload()204 {205     if (pindexBest == NULL)206@@ -866,17 +899,10 @@207         nLastUpdate = GetTime();208     }209     return (GetTime() - nLastUpdate < 10 &&210-            pindexBest->nTime < GetTime() - 24 * 60 * 60);211-}212-213-bool IsLockdown()214-{215-    if (!pindexBest)216-        return false;217-    return (bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6);218-}219-220-void Lockdown(CBlockIndex* pindexNew)221+            pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);222+}223+224+void InvalidChainFound(CBlockIndex* pindexNew)225 {226     if (pindexNew->bnChainWork > bnBestInvalidWork)227     {228@@ -884,12 +910,14 @@229         CTxDB().WriteBestInvalidWork(bnBestInvalidWork);230         MainFrameRepaint();231     }232-    printf("Lockdown: invalid block=%s  height=%d  work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,22).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());233-    printf("Lockdown:  current best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,22).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());234-    printf("Lockdown: IsLockdown()=%d\n", (IsLockdown() ? 1 : 0));235-    if (IsLockdown())236-        printf("Lockdown: WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.\n");237-}238+    printf("InvalidChainFound: invalid block=%s  height=%d  work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());239+    printf("InvalidChainFound:  current best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());240+    if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)241+        printf("InvalidChainFound: WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.\n");242+}243+244+245+246 247 248 249@@ -1008,13 +1036,12 @@250             nValueIn += txPrev.vout[prevout.n].nValue;251 252             // Check for negative or overflow input values253-            if (txPrev.vout[prevout.n].nValue < 0)254-                return error("ConnectInputs() : txin.nValue negative");255-            if (txPrev.vout[prevout.n].nValue > MAX_MONEY)256-                return error("ConnectInputs() : txin.nValue too high");257-            if (nValueIn > MAX_MONEY)258-                return error("ConnectInputs() : txin total too high");259-        }260+            if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))261+                return error("ConnectInputs() : txin values out of range");262+        }263+264+        if (nValueIn < GetValueOut())265+            return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,6).c_str());266 267         // Tally transaction fees268         int64 nTxFee = nValueIn - GetValueOut();269@@ -1023,6 +1050,8 @@270         if (nTxFee < nMinFee)271             return false;272         nFees += nTxFee;273+        if (!MoneyRange(nFees))274+            return error("ConnectInputs() : nFees out of range");275     }276 277     if (fBlock)278@@ -1075,6 +1104,9 @@279             // txPrev.vout[prevout.n].posNext = posThisTx;280 281             nValueIn += txPrev.vout[prevout.n].nValue;282+283+            if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))284+                return error("ClientConnectInputs() : txin values out of range");285         }286         if (GetValueOut() > nValueIn)287             return false;288@@ -1107,6 +1139,10 @@289 290 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)291 {292+    // Check it again in case a previous version let a bad block in293+    if (!CheckBlock())294+        return false;295+296     //// issue here: it doesn't know the version297     unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());298 299@@ -1176,7 +1212,7 @@300     foreach(CBlockIndex* pindex, vDisconnect)301     {302         CBlock block;303-        if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))304+        if (!block.ReadFromDisk(pindex))305             return error("Reorganize() : ReadFromDisk for disconnect failed");306         if (!block.DisconnectBlock(txdb, pindex))307             return error("Reorganize() : DisconnectBlock failed");308@@ -1193,7 +1229,7 @@309     {310         CBlockIndex* pindex = vConnect[i];311         CBlock block;312-        if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))313+        if (!block.ReadFromDisk(pindex))314             return error("Reorganize() : ReadFromDisk for connect failed");315         if (!block.ConnectBlock(txdb, pindex))316         {317@@ -1224,7 +1260,7 @@318 319     // Resurrect memory transactions that were in the disconnected branch320     foreach(CTransaction& tx, vResurrect)321-        tx.AcceptTransaction(txdb, false);322+        tx.AcceptToMemoryPool(txdb, false);323 324     // Delete redundant memory transactions that are in the connected branch325     foreach(CTransaction& tx, vDelete)326@@ -1234,12 +1270,63 @@327 }328 329 330+bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)331+{332+    uint256 hash = GetHash();333+334+    txdb.TxnBegin();335+    if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)336+    {337+        pindexGenesisBlock = pindexNew;338+        txdb.WriteHashBestChain(hash);339+    }340+    else if (hashPrevBlock == hashBestChain)341+    {342+        // Adding to current best branch343+        if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))344+        {345+            txdb.TxnAbort();346+            InvalidChainFound(pindexNew);347+            return error("SetBestChain() : ConnectBlock failed");348+        }349+        txdb.TxnCommit();350+        pindexNew->pprev->pnext = pindexNew;351+352+        // Delete redundant memory transactions353+        foreach(CTransaction& tx, vtx)354+            tx.RemoveFromMemoryPool();355+    }356+    else357+    {358+        // New best branch359+        if (!Reorganize(txdb, pindexNew))360+        {361+            txdb.TxnAbort();362+            InvalidChainFound(pindexNew);363+            return error("SetBestChain() : Reorganize failed");364+        }365+    }366+    txdb.TxnCommit();367+368+    // New best block369+    hashBestChain = hash;370+    pindexBest = pindexNew;371+    nBestHeight = pindexBest->nHeight;372+    bnBestChainWork = pindexNew->bnChainWork;373+    nTimeBestReceived = GetTime();374+    nTransactionsUpdated++;375+    printf("SetBestChain: new best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());376+377+    return true;378+}379+380+381 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)382 {383     // Check for duplicate384     uint256 hash = GetHash();385     if (mapBlockIndex.count(hash))386-        return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,16).c_str());387+        return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());388 389     // Construct new block index object390     CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);391@@ -1260,50 +1347,8 @@392 393     // New best394     if (pindexNew->bnChainWork > bnBestChainWork)395-    {396-        txdb.TxnBegin();397-        if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)398-        {399-            pindexGenesisBlock = pindexNew;400-            txdb.WriteHashBestChain(hash);401-        }402-        else if (hashPrevBlock == hashBestChain)403-        {404-            // Adding to current best branch405-            if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))406-            {407-                txdb.TxnAbort();408-                Lockdown(pindexNew);409-                return error("AddToBlockIndex() : ConnectBlock failed");410-            }411-            txdb.TxnCommit();412-            pindexNew->pprev->pnext = pindexNew;413-414-            // Delete redundant memory transactions415-            foreach(CTransaction& tx, vtx)416-                tx.RemoveFromMemoryPool();417-        }418-        else419-        {420-            // New best branch421-            if (!Reorganize(txdb, pindexNew))422-            {423-                txdb.TxnAbort();424-                Lockdown(pindexNew);425-                return error("AddToBlockIndex() : Reorganize failed");426-            }427-        }428-        txdb.TxnCommit();429-430-        // New best block431-        hashBestChain = hash;432-        pindexBest = pindexNew;433-        nBestHeight = pindexBest->nHeight;434-        bnBestChainWork = pindexNew->bnChainWork;435-        nTimeBestReceived = GetTime();436-        nTransactionsUpdated++;437-        printf("AddToBlockIndex: new best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,22).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());438-    }439+        if (!SetBestChain(txdb, pindexNew))440+            return false;441 442     txdb.Close();443 444@@ -1329,11 +1374,11 @@445     // that can be verified before saving an orphan block.446 447     // Size limits448-    if (vtx.empty() || vtx.size() > MAX_SIZE || ::GetSerializeSize(*this, SER_DISK) > MAX_SIZE)449+    if (vtx.empty() || vtx.size() > MAX_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_SIZE)450         return error("CheckBlock() : size limits failed");451 452     // Check timestamp453-    if (nTime > GetAdjustedTime() + 2 * 60 * 60)454+    if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)455         return error("CheckBlock() : block timestamp too far in the future");456 457     // First transaction must be coinbase, the rest must not be458@@ -1349,10 +1394,8 @@459             return error("CheckBlock() : CheckTransaction failed");460 461     // Check proof of work matches claimed amount462-    if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)463-        return error("CheckBlock() : nBits below minimum work");464-    if (GetHash() > CBigNum().SetCompact(nBits).getuint256())465-        return error("CheckBlock() : hash doesn't match nBits");466+    if (!CheckProofOfWork(GetHash(), nBits))467+        return error("CheckBlock() : proof of work failed");468 469     // Check merkleroot470     if (hashMerkleRoot != BuildMerkleTree())471@@ -1373,14 +1416,23 @@472     if (mi == mapBlockIndex.end())473         return error("AcceptBlock() : prev block not found");474     CBlockIndex* pindexPrev = (*mi).second;475+    int nHeight = pindexPrev->nHeight+1;476+477+    // Check size478+    if (nHeight > 79400 && ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)479+        return error("AcceptBlock() : over size limit");480+481+    // Check that it's not full of nonstandard transactions482+    if (nHeight > 79400 && GetSigOpCount() > MAX_BLOCK_SIGOPS)483+        return error("AcceptBlock() : too many nonstandard transactions");484 485     // Check timestamp against prev486-    if (nTime <= pindexPrev->GetMedianTimePast())487+    if (GetBlockTime() <= pindexPrev->GetMedianTimePast())488         return error("AcceptBlock() : block's timestamp is too early");489 490     // Check that all transactions are finalized491     foreach(const CTransaction& tx, vtx)492-        if (!tx.IsFinal(pindexPrev->nHeight+1, nTime))493+        if (!tx.IsFinal(nHeight, GetBlockTime()))494             return error("AcceptBlock() : contains a non-final transaction");495 496     // Check proof of work497@@ -1388,12 +1440,12 @@498         return error("AcceptBlock() : incorrect proof of work");499 500     // Check that the block chain matches the known block chain up to a checkpoint501-    if ((pindexPrev->nHeight+1 == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||502-        (pindexPrev->nHeight+1 == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||503-        (pindexPrev->nHeight+1 == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||504-        (pindexPrev->nHeight+1 == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||505-        (pindexPrev->nHeight+1 == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")))506-        return error("AcceptBlock() : rejected by checkpoint lockin at %d", pindexPrev->nHeight+1);507+    if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||508+        (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||509+        (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||510+        (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||511+        (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")))512+        return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);513 514     // Scanback checkpoint lockin515     for (CBlockIndex* pindex = pindexPrev; pindex->nHeight >= 74000; pindex = pindex->pprev)516@@ -1429,9 +1481,9 @@517     // Check for duplicate518     uint256 hash = pblock->GetHash();519     if (mapBlockIndex.count(hash))520-        return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,16).c_str());521+        return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());522     if (mapOrphanBlocks.count(hash))523-        return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,16).c_str());524+        return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());525 526     // Preliminary checks527     if (!pblock->CheckBlock())528@@ -1443,7 +1495,7 @@529     // If don't already have its previous block, shunt it off to holding area until we get it530     if (!mapBlockIndex.count(pblock->hashPrevBlock))531     {532-        printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,16).c_str());533+        printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());534         mapOrphanBlocks.insert(make_pair(hash, pblock));535         mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));536 537@@ -1532,18 +1584,18 @@538     }539 }540 541-bool CheckDiskSpace(int64 nAdditionalBytes)542+bool CheckDiskSpace(uint64 nAdditionalBytes)543 {544     uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;545 546     // Check for 15MB because database could create another 10MB log file at any time547-    if (nFreeBytesAvailable < (int64)15000000 + nAdditionalBytes)548+    if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)549     {550         fShutdown = true;551-        printf("***  %s***\n", _("Warning: Disk space is low  "));552-#ifdef GUI553-        ThreadSafeMessageBox(_("Warning: Disk space is low  "), "Bitcoin", wxOK | wxICON_EXCLAMATION);554-#endif555+        string strMessage = _("Warning: Disk space is low  ");556+        strMiscWarning = strMessage;557+        printf("*** %s\n", strMessage.c_str());558+        ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);559         CreateThread(Shutdown, NULL);560         return false;561     }562@@ -1609,17 +1661,7 @@563         if (!fAllowNew)564             return false;565 566-567         // Genesis Block:568-        // GetHash()      = 0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f569-        // hashMerkleRoot = 0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b570-        // txNew.vin[0].scriptSig     = 486604799 4 0x736B6E616220726F662074756F6C69616220646E6F63657320666F206B6E697262206E6F20726F6C6C65636E61684320393030322F6E614A2F33302073656D695420656854571-        // txNew.vout[0].nValue       = 5000000000572-        // txNew.vout[0].scriptPubKey = 0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704 OP_CHECKSIG573-        // block.nVersion = 1574-        // block.nTime    = 1231006505575-        // block.nBits    = 0x1d00ffff576-        // block.nNonce   = 2083236893577         // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)578         //   CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)579         //     CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)580@@ -1633,9 +1675,7 @@581         txNew.vout.resize(1);582         txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));583         txNew.vout[0].nValue = 50 * COIN;584-        CBigNum bnPubKey;585-        bnPubKey.SetHex("0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704");586-        txNew.vout[0].scriptPubKey = CScript() << bnPubKey << OP_CHECKSIG;587+        txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;588         CBlock block;589         block.vtx.push_back(txNew);590         block.hashPrevBlock = 0;591@@ -1647,11 +1687,10 @@592 593             //// debug print594             printf("%s\n", block.GetHash().ToString().c_str());595+            printf("%s\n", hashGenesisBlock.ToString().c_str());596             printf("%s\n", block.hashMerkleRoot.ToString().c_str());597-            printf("%s\n", hashGenesisBlock.ToString().c_str());598-            txNew.vout[0].scriptPubKey.print();599+            assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));600             block.print();601-            assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));602 603         assert(block.GetHash() == hashGenesisBlock);604 605@@ -1718,8 +1757,8 @@606             pindex->nHeight,607             pindex->nFile,608             pindex->nBlockPos,609-            block.GetHash().ToString().substr(0,16).c_str(),610-            DateTimeStrFormat("%x %H:%M:%S", block.nTime).c_str(),611+            block.GetHash().ToString().substr(0,20).c_str(),612+            DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),613             block.vtx.size());614 615         CRITICAL_BLOCK(cs_mapWallet)616@@ -1751,6 +1790,113 @@617 }618 619 620+621+622+623+624+625+626+627+628+//////////////////////////////////////////////////////////////////////////////629+//630+// CAlert631+//632+633+map<uint256, CAlert> mapAlerts;634+CCriticalSection cs_mapAlerts;635+636+string GetWarnings(string strFor)637+{638+    int nPriority = 0;639+    string strStatusBar;640+    string strRPC;641+    if (mapArgs.count("-testsafemode"))642+        strRPC = "test";643+644+    // Misc warnings like out of disk space and clock is wrong645+    if (strMiscWarning != "")646+    {647+        nPriority = 1000;648+        strStatusBar = strMiscWarning;649+    }650+651+    // Longer invalid proof-of-work chain652+    if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)653+    {654+        nPriority = 2000;655+        strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.";656+    }657+658+    // Alerts659+    CRITICAL_BLOCK(cs_mapAlerts)660+    {661+        foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)662+        {663+            const CAlert& alert = item.second;664+            if (alert.AppliesToMe() && alert.nPriority > nPriority)665+            {666+                nPriority = alert.nPriority;667+                strStatusBar = alert.strStatusBar;668+                strRPC = alert.strRPCError;669+            }670+        }671+    }672+673+    if (strFor == "statusbar")674+        return strStatusBar;675+    else if (strFor == "rpc")676+        return strRPC;677+    assert(("GetWarnings() : invalid parameter", false));678+    return "error";679+}680+681+bool CAlert::ProcessAlert()682+{683+    if (!CheckSignature())684+        return false;685+    if (!IsInEffect())686+        return false;687+688+    CRITICAL_BLOCK(cs_mapAlerts)689+    {690+        // Cancel previous alerts691+        for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)692+        {693+            const CAlert& alert = (*mi).second;694+            if (Cancels(alert))695+            {696+                printf("cancelling alert %d\n", alert.nID);697+                mapAlerts.erase(mi++);698+            }699+            else if (!alert.IsInEffect())700+            {701+                printf("expiring alert %d\n", alert.nID);702+                mapAlerts.erase(mi++);703+            }704+            else705+                mi++;706+        }707+708+        // Check if this alert has been cancelled709+        foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)710+        {711+            const CAlert& alert = item.second;712+            if (alert.Cancels(*this))713+            {714+                printf("alert already cancelled by %d\n", alert.nID);715+                return false;716+            }717+        }718+719+        // Add to mapAlerts720+        mapAlerts.insert(make_pair(GetHash(), *this));721+    }722+723+    printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());724+    MainFrameRepaint();725+    return true;726+}727 728 729 730@@ -1788,7 +1934,7 @@731     if (vRecv.empty())732         return true;733     //if (fDebug)734-    //    printf("ProcessMessages(%d bytes)\n", vRecv.size());735+    //    printf("ProcessMessages(%u bytes)\n", vRecv.size());736 737     //738     // Message format739@@ -1830,6 +1976,11 @@740 741         // Message size742         unsigned int nMessageSize = hdr.nMessageSize;743+        if (nMessageSize > MAX_SIZE)744+        {745+            printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);746+            continue;747+        }748         if (nMessageSize > vRecv.size())749         {750             // Rewind and wait for rest of message751@@ -1850,7 +2001,7 @@752             memcpy(&nChecksum, &hash, sizeof(nChecksum));753             if (nChecksum != hdr.nChecksum)754             {755-                printf("ProcessMessage(%s, %d bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",756+                printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",757                        strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);758                 continue;759             }760@@ -1867,29 +2018,29 @@761         }762         catch (std::ios_base::failure& e)763         {764-            if (strstr(e.what(), "CDataStream::read() : end of data"))765+            if (strstr(e.what(), "end of data"))766             {767                 // Allow exceptions from underlength message on vRecv768-                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());769-            }770-            else if (strstr(e.what(), ": size too large"))771+                printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());772+            }773+            else if (strstr(e.what(), "size too large"))774             {775                 // Allow exceptions from overlong size776-                printf("ProcessMessage(%s, %d bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());777+                printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());778             }779             else780             {781-                PrintException(&e, "ProcessMessage()");782+                PrintExceptionContinue(&e, "ProcessMessage()");783             }784         }785         catch (std::exception& e) {786-            PrintException(&e, "ProcessMessage()");787+            PrintExceptionContinue(&e, "ProcessMessage()");788         } catch (...) {789-            PrintException(NULL, "ProcessMessage()");790+            PrintExceptionContinue(NULL, "ProcessMessage()");791         }792 793         if (!fRet)794-            printf("ProcessMessage(%s, %d bytes) FAILED\n", strCommand.c_str(), nMessageSize);795+            printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);796     }797 798     vRecv.Compact();799@@ -1926,14 +2077,13 @@800         CAddress addrMe;801         CAddress addrFrom;802         uint64 nNonce = 1;803-        string strSubVer;804         vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;805         if (pfrom->nVersion == 10300)806             pfrom->nVersion = 300;807         if (pfrom->nVersion >= 106 && !vRecv.empty())808             vRecv >> addrFrom >> nNonce;809         if (pfrom->nVersion >= 106 && !vRecv.empty())810-            vRecv >> strSubVer;811+            vRecv >> pfrom->strSubVer;812         if (pfrom->nVersion >= 209 && !vRecv.empty())813             vRecv >> pfrom->nStartingHeight;814 815@@ -1970,6 +2120,11 @@816             nAskedForBlocks++;817             pfrom->PushGetBlocks(pindexBest, uint256(0));818         }819+820+        // Relay alerts821+        CRITICAL_BLOCK(cs_mapAlerts)822+            foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)823+                item.second.RelayTo(pfrom);824 825         pfrom->fSuccessfullyConnected = true;826 827@@ -2028,7 +2183,7 @@828                     multimap<uint256, CNode*> mapMix;829                     foreach(CNode* pnode, vNodes)830                         mapMix.insert(make_pair(hashRand = Hash(BEGIN(hashRand), END(hashRand)), pnode));831-                    int nRelayNodes = 4;832+                    int nRelayNodes = 2;833                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)834                         ((*mi).second)->PushAddress(addr);835                 }836@@ -2144,12 +2299,12 @@837         if (pindex)838             pindex = pindex->pnext;839         int nLimit = 500 + locator.GetDistanceBack();840-        printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,16).c_str(), nLimit);841+        printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);842         for (; pindex; pindex = pindex->pnext)843         {844             if (pindex->GetBlockHash() == hashStop)845             {846-                printf("  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());847+                printf("  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());848                 break;849             }850             pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));851@@ -2157,7 +2312,7 @@852             {853                 // When this block is requested, we'll send an inv that'll make them854                 // getblocks the next batch of inventory.855-                printf("  getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());856+                printf("  getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());857                 pfrom->hashContinue = pindex->GetBlockHash();858                 break;859             }860@@ -2176,7 +2331,7 @@861         pfrom->AddInventoryKnown(inv);862 863         bool fMissingInputs = false;864-        if (tx.AcceptTransaction(true, &fMissingInputs))865+        if (tx.AcceptToMemoryPool(true, &fMissingInputs))866         {867             AddToWalletIfMine(tx, NULL);868             RelayMessage(inv, vMsg);869@@ -2196,7 +2351,7 @@870                     CDataStream(vMsg) >> tx;871                     CInv inv(MSG_TX, tx.GetHash());872 873-                    if (tx.AcceptTransaction(true))874+                    if (tx.AcceptToMemoryPool(true))875                     {876                         printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());877                         AddToWalletIfMine(tx, NULL);878@@ -2224,7 +2379,7 @@879         vRecv >> *pblock;880 881         //// debug print882-        printf("received block %s\n", pblock->GetHash().ToString().substr(0,16).c_str());883+        printf("received block %s\n", pblock->GetHash().ToString().substr(0,20).c_str());884         // pblock->print();885 886         CInv inv(MSG_BLOCK, pblock->GetHash());887@@ -2320,6 +2475,22 @@888 889     else if (strCommand == "ping")890     {891+    }892+893+894+    else if (strCommand == "alert")895+    {896+        CAlert alert;897+        vRecv >> alert;898+899+        if (alert.ProcessAlert())900+        {901+            // Relay902+            pfrom->setKnown.insert(alert.GetHash());903+            CRITICAL_BLOCK(cs_vNodes)904+                foreach(CNode* pnode, vNodes)905+                    alert.RelayTo(pnode);906+        }907     }908 909 910@@ -2656,8 +2827,9 @@911             map<uint256, CTxIndex> mapTestPool;912             vector<char> vfAlreadyAdded(mapTransactions.size());913             bool fFoundSomething = true;914-            unsigned int nBlockSize = 0;915-            while (fFoundSomething && nBlockSize < MAX_SIZE/2)916+            uint64 nBlockSize = 10000;917+            int nBlockSigOps = 100;918+            while (fFoundSomething)919             {920                 fFoundSomething = false;921                 unsigned int n = 0;922@@ -2669,7 +2841,10 @@923                     if (tx.IsCoinBase() || !tx.IsFinal())924                         continue;925                     unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);926-                    if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE - 10000)927+                    if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE)928+                        continue;929+                    int nTxSigOps = tx.GetSigOpCount();930+                    if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)931                         continue;932 933                     // Transaction fee based on block size934@@ -2682,6 +2857,7 @@935 936                     pblock->vtx.push_back(tx);937                     nBlockSize += nTxSize;938+                    nBlockSigOps += nTxSigOps;939                     vfAlreadyAdded[n] = true;940                     fFoundSomething = true;941                 }942@@ -3144,7 +3320,7 @@943 944             // Add the change's private key to wallet945             if (!key.IsNull() && !AddKey(key))946-                throw runtime_error("CommitTransaction() : AddKey failed\n");947+                throw runtime_error("CommitTransaction() : AddKey failed");948 949             // Add tx to wallet, because if it has change it's also ours,950             // otherwise just for transaction history.951@@ -3167,7 +3343,7 @@952             mapRequestCount[wtxNew.GetHash()] = 0;953 954         // Broadcast955-        if (!wtxNew.AcceptTransaction())956+        if (!wtxNew.AcceptToMemoryPool())957         {958             // This must not fail. The transaction has already been signed and recorded.959             printf("CommitTransaction() : Error: Transaction not valid");

main.h (modified)

1--- v0.3.10/main.h2+++ v0.3.12/main.h3@@ -14,13 +14,13 @@4 class CWalletTx;5 class CKeyItem;6 7-static const unsigned int MAX_SIZE = 0x02000000;8 static const unsigned int MAX_BLOCK_SIZE = 1000000;9+static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;10 static const int64 COIN = 100000000;11 static const int64 CENT = 1000000;12 static const int64 MAX_MONEY = 21000000 * COIN;13+inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }14 static const int COINBASE_MATURITY = 100;15-16 static const CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);17 18 19@@ -61,7 +61,7 @@20 21 22 23-bool CheckDiskSpace(int64 nAdditionalBytes=0);24+bool CheckDiskSpace(uint64 nAdditionalBytes=0);25 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");26 FILE* AppendBlockFile(unsigned int& nFileRet);27 bool AddKey(const CKey& key);28@@ -83,8 +83,9 @@29 void GenerateBitcoins(bool fGenerate);30 void ThreadBitcoinMiner(void* parg);31 void BitcoinMiner();32+bool CheckProofOfWork(uint256 hash, unsigned int nBits);33 bool IsInitialBlockDownload();34-bool IsLockdown();35+string GetWarnings(string strFor);36 37 38 39@@ -266,7 +267,7 @@40         str += strprintf("CTxIn(");41         str += prevout.ToString();42         if (prevout.IsNull())43-            str += strprintf(", coinbase %s", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str());44+            str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());45         else46             str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());47         if (nSequence != UINT_MAX)48@@ -297,7 +298,6 @@49     int64 nValue;50     CScript scriptPubKey;51 52-public:53     CTxOut()54     {55         SetNull();56@@ -338,6 +338,8 @@57 58     int64 GetCredit() const59     {60+        if (!MoneyRange(nValue))61+            throw runtime_error("CTxOut::GetCredit() : value out of range");62         if (IsMine())63             return nValue;64         return 0;65@@ -424,7 +426,7 @@66             nBlockHeight = nBestHeight;67         if (nBlockTime == 0)68             nBlockTime = GetAdjustedTime();69-        if (nLockTime < (nLockTime < 500000000 ? nBlockHeight : nBlockTime))70+        if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))71             return true;72         foreach(const CTxIn& txin, vin)73             if (!txin.IsFinal())74@@ -472,6 +474,10 @@75         if (vin.empty() || vout.empty())76             return error("CTransaction::CheckTransaction() : vin or vout empty");77 78+        // Size limits79+        if (::GetSerializeSize(*this, SER_NETWORK) > MAX_SIZE)80+            return error("CTransaction::CheckTransaction() : size limits failed");81+82         // Check for negative or overflow output values83         int64 nValueOut = 0;84         foreach(const CTxOut& txout, vout)85@@ -481,8 +487,8 @@86             if (txout.nValue > MAX_MONEY)87                 return error("CTransaction::CheckTransaction() : txout.nValue too high");88             nValueOut += txout.nValue;89-            if (nValueOut > MAX_MONEY)90-                return error("CTransaction::CheckTransaction() : txout total too high");91+            if (!MoneyRange(nValueOut))92+                return error("CTransaction::CheckTransaction() : txout total out of range");93         }94 95         if (IsCoinBase())96@@ -498,6 +504,16 @@97         }98 99         return true;100+    }101+102+    int GetSigOpCount() const103+    {104+        int n = 0;105+        foreach(const CTxIn& txin, vin)106+            n += txin.scriptSig.GetSigOpCount();107+        foreach(const CTxOut& txout, vout)108+            n += txout.scriptPubKey.GetSigOpCount();109+        return n;110     }111 112     bool IsMine() const113@@ -512,7 +528,11 @@114     {115         int64 nDebit = 0;116         foreach(const CTxIn& txin, vin)117+        {118             nDebit += txin.GetDebit();119+            if (!MoneyRange(nDebit))120+                throw runtime_error("CTransaction::GetDebit() : value out of range");121+        }122         return nDebit;123     }124 125@@ -520,7 +540,11 @@126     {127         int64 nCredit = 0;128         foreach(const CTxOut& txout, vout)129+        {130             nCredit += txout.GetCredit();131+            if (!MoneyRange(nCredit))132+                throw runtime_error("CTransaction::GetCredit() : value out of range");133+        }134         return nCredit;135     }136 137@@ -529,9 +553,9 @@138         int64 nValueOut = 0;139         foreach(const CTxOut& txout, vout)140         {141-            if (txout.nValue < 0)142-                throw runtime_error("CTransaction::GetValueOut() : negative value");143             nValueOut += txout.nValue;144+            if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))145+                throw runtime_error("CTransaction::GetValueOut() : value out of range");146         }147         return nValueOut;148     }149@@ -557,9 +581,14 @@150                 if (txout.nValue < CENT)151                     nMinFee = CENT;152 153+        // Raise the price as the block approaches full154+        if (MAX_BLOCK_SIZE/2 <= nBlockSize && nBlockSize < MAX_BLOCK_SIZE)155+            nMinFee *= MAX_BLOCK_SIZE / (MAX_BLOCK_SIZE - nBlockSize);156+        if (!MoneyRange(nMinFee))157+            nMinFee = MAX_MONEY;158+159         return nMinFee;160     }161-162 163 164     bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)165@@ -626,16 +655,16 @@166                        CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);167     bool ClientConnectInputs();168 169-    bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);170-171-    bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)172+    bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);173+174+    bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)175     {176         CTxDB txdb("r");177-        return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);178+        return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);179     }180 181 protected:182-    bool AddToMemoryPool();183+    bool AddToMemoryPoolUnchecked();184 public:185     bool RemoveFromMemoryPool();186 };187@@ -708,8 +737,8 @@188     int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }189     bool IsInMainChain() const { return GetDepthInMainChain() > 0; }190     int GetBlocksToMaturity() const;191-    bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);192-    bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }193+    bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);194+    bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }195 };196 197 198@@ -839,12 +868,8 @@199 200     friend bool operator==(const CTxIndex& a, const CTxIndex& b)201     {202-        if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())203-            return false;204-        for (int i = 0; i < a.vSpent.size(); i++)205-            if (a.vSpent[i] != b.vSpent[i])206-                return false;207-        return true;208+        return (a.pos    == b.pos &&209+                a.vSpent == b.vSpent);210     }211 212     friend bool operator!=(const CTxIndex& a, const CTxIndex& b)213@@ -930,6 +955,19 @@214         return Hash(BEGIN(nVersion), END(nNonce));215     }216 217+    int64 GetBlockTime() const218+    {219+        return (int64)nTime;220+    }221+222+    int GetSigOpCount() const223+    {224+        int n = 0;225+        foreach(const CTransaction& tx, vtx)226+            n += tx.GetSigOpCount();227+        return n;228+    }229+230 231     uint256 BuildMerkleTree() const232     {233@@ -1030,10 +1068,8 @@234         filein >> *this;235 236         // Check the header237-        if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)238-            return error("CBlock::ReadFromDisk() : nBits errors in block header");239-        if (GetHash() > CBigNum().SetCompact(nBits).getuint256())240-            return error("CBlock::ReadFromDisk() : GetHash() errors in block header");241+        if (!CheckProofOfWork(GetHash(), nBits))242+            return error("CBlock::ReadFromDisk() : errors in block header");243 244         return true;245     }246@@ -1043,9 +1079,9 @@247     void print() const248     {249         printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",250-            GetHash().ToString().substr(0,16).c_str(),251+            GetHash().ToString().substr(0,20).c_str(),252             nVersion,253-            hashPrevBlock.ToString().substr(0,16).c_str(),254+            hashPrevBlock.ToString().substr(0,20).c_str(),255             hashMerkleRoot.ToString().substr(0,6).c_str(),256             nTime, nBits, nNonce,257             vtx.size());258@@ -1064,7 +1100,8 @@259     int64 GetBlockValue(int nHeight, int64 nFees) const;260     bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);261     bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);262-    bool ReadFromDisk(const CBlockIndex* blockindex, bool fReadTransactions=true);263+    bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);264+    bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);265     bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);266     bool CheckBlock() const;267     bool AcceptBlock();268@@ -1141,14 +1178,26 @@269         return *phashBlock;270     }271 272+    int64 GetBlockTime() const273+    {274+        return (int64)nTime;275+    }276+277     CBigNum GetBlockWork() const278     {279+        if (CBigNum().SetCompact(nBits) <= 0)280+            return 0;281         return (CBigNum(1)<<256) / (CBigNum().SetCompact(nBits)+1);282     }283 284     bool IsInMainChain() const285     {286         return (pnext || this == pindexBest);287+    }288+289+    bool CheckIndex() const290+    {291+        return CheckProofOfWork(GetBlockHash(), nBits);292     }293 294     bool EraseBlockFromDisk()295@@ -1170,13 +1219,13 @@296 297     int64 GetMedianTimePast() const298     {299-        unsigned int pmedian[nMedianTimeSpan];300-        unsigned int* pbegin = &pmedian[nMedianTimeSpan];301-        unsigned int* pend = &pmedian[nMedianTimeSpan];302+        int64 pmedian[nMedianTimeSpan];303+        int64* pbegin = &pmedian[nMedianTimeSpan];304+        int64* pend = &pmedian[nMedianTimeSpan];305 306         const CBlockIndex* pindex = this;307         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)308-            *(--pbegin) = pindex->nTime;309+            *(--pbegin) = pindex->GetBlockTime();310 311         sort(pbegin, pend);312         return pbegin[(pend - pbegin)/2];313@@ -1188,7 +1237,7 @@314         for (int i = 0; i < nMedianTimeSpan/2; i++)315         {316             if (!pindex->pnext)317-                return nTime;318+                return GetBlockTime();319             pindex = pindex->pnext;320         }321         return pindex->GetMedianTimePast();322@@ -1201,7 +1250,7 @@323         return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",324             pprev, pnext, nFile, nBlockPos, nHeight,325             hashMerkleRoot.ToString().substr(0,6).c_str(),326-            GetBlockHash().ToString().substr(0,16).c_str());327+            GetBlockHash().ToString().substr(0,20).c_str());328     }329 330     void print() const331@@ -1271,8 +1320,8 @@332         str += CBlockIndex::ToString();333         str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",334             GetBlockHash().ToString().c_str(),335-            hashPrev.ToString().substr(0,16).c_str(),336-            hashNext.ToString().substr(0,16).c_str());337+            hashPrev.ToString().substr(0,20).c_str(),338+            hashNext.ToString().substr(0,20).c_str());339         return str;340     }341 342@@ -1442,6 +1491,214 @@343 344 345 346+//347+// Alert messages are broadcast as a vector of signed data.  Unserializing may348+// not read the entire buffer if the alert is for a newer version, but older349+// versions can still relay the original data.350+//351+class CUnsignedAlert352+{353+public:354+    int nVersion;355+    int64 nRelayUntil;      // when newer nodes stop relaying to newer nodes356+    int64 nExpiration;357+    int nID;358+    int nCancel;359+    set<int> setCancel;360+    int nMinVer;            // lowest version inclusive361+    int nMaxVer;            // highest version inclusive362+    set<string> setSubVer;  // empty matches all363+    int nPriority;364+365+    // Actions366+    string strComment;367+    string strStatusBar;368+    string strRPCError;369+370+    IMPLEMENT_SERIALIZE371+    (372+        READWRITE(this->nVersion);373+        nVersion = this->nVersion;374+        READWRITE(nRelayUntil);375+        READWRITE(nExpiration);376+        READWRITE(nID);377+        READWRITE(nCancel);378+        READWRITE(setCancel);379+        READWRITE(nMinVer);380+        READWRITE(nMaxVer);381+        READWRITE(setSubVer);382+        READWRITE(nPriority);383+384+        READWRITE(strComment);385+        READWRITE(strStatusBar);386+        READWRITE(strRPCError);387+    )388+389+    void SetNull()390+    {391+        nVersion = 1;392+        nRelayUntil = 0;393+        nExpiration = 0;394+        nID = 0;395+        nCancel = 0;396+        setCancel.clear();397+        nMinVer = 0;398+        nMaxVer = 0;399+        setSubVer.clear();400+        nPriority = 0;401+402+        strComment.clear();403+        strStatusBar.clear();404+        strRPCError.clear();405+    }406+407+    string ToString() const408+    {409+        string strSetCancel;410+        foreach(int n, setCancel)411+            strSetCancel += strprintf("%d ", n);412+        string strSetSubVer;413+        foreach(string str, setSubVer)414+            strSetSubVer += "\"" + str + "\" ";415+        return strprintf(416+                "CAlert(\n"417+                "    nVersion     = %d\n"418+                "    nRelayUntil  = %"PRI64d"\n"419+                "    nExpiration  = %"PRI64d"\n"420+                "    nID          = %d\n"421+                "    nCancel      = %d\n"422+                "    setCancel    = %s\n"423+                "    nMinVer      = %d\n"424+                "    nMaxVer      = %d\n"425+                "    setSubVer    = %s\n"426+                "    nPriority    = %d\n"427+                "    strComment   = \"%s\"\n"428+                "    strStatusBar = \"%s\"\n"429+                "    strRPCError  = \"%s\"\n"430+                ")\n",431+            nVersion,432+            nRelayUntil,433+            nExpiration,434+            nID,435+            nCancel,436+            strSetCancel.c_str(),437+            nMinVer,438+            nMaxVer,439+            strSetSubVer.c_str(),440+            nPriority,441+            strComment.c_str(),442+            strStatusBar.c_str(),443+            strRPCError.c_str());444+    }445+446+    void print() const447+    {448+        printf("%s", ToString().c_str());449+    }450+};451+452+class CAlert : public CUnsignedAlert453+{454+public:455+    vector<unsigned char> vchMsg;456+    vector<unsigned char> vchSig;457+458+    CAlert()459+    {460+        SetNull();461+    }462+463+    IMPLEMENT_SERIALIZE464+    (465+        READWRITE(vchMsg);466+        READWRITE(vchSig);467+    )468+469+    void SetNull()470+    {471+        CUnsignedAlert::SetNull();472+        vchMsg.clear();473+        vchSig.clear();474+    }475+476+    bool IsNull() const477+    {478+        return (nExpiration == 0);479+    }480+481+    uint256 GetHash() const482+    {483+        return SerializeHash(*this);484+    }485+486+    bool IsInEffect() const487+    {488+        return (GetAdjustedTime() < nExpiration);489+    }490+491+    bool Cancels(const CAlert& alert) const492+    {493+        if (!IsInEffect())494+            false;495+        return (alert.nID <= nCancel || setCancel.count(alert.nID));496+    }497+498+    bool AppliesTo(int nVersion, string strSubVerIn) const499+    {500+        return (IsInEffect() &&501+                nMinVer <= nVersion && nVersion <= nMaxVer &&502+                (setSubVer.empty() || setSubVer.count(strSubVerIn)));503+    }504+505+    bool AppliesToMe() const506+    {507+        return AppliesTo(VERSION, ::pszSubVer);508+    }509+510+    bool RelayTo(CNode* pnode) const511+    {512+        if (!IsInEffect())513+            return false;514+        // returns true if wasn't already contained in the set515+        if (pnode->setKnown.insert(GetHash()).second)516+        {517+            if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||518+                AppliesToMe() ||519+                GetAdjustedTime() < nRelayUntil)520+            {521+                pnode->PushMessage("alert", *this);522+                return true;523+            }524+        }525+        return false;526+    }527+528+    bool CheckSignature()529+    {530+        CKey key;531+        if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))532+            return error("CAlert::CheckSignature() : SetPubKey failed");533+        if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))534+            return error("CAlert::CheckSignature() : verify signature failed");535+536+        // Now unserialize the data537+        CDataStream sMsg(vchMsg);538+        sMsg >> *(CUnsignedAlert*)this;539+        return true;540+    }541+542+    bool ProcessAlert();543+};544+545+546+547+548+549+550+551+552+553+554 extern map<uint256, CTransaction> mapTransactions;555 extern map<uint256, CWalletTx> mapWallet;556 extern vector<uint256> vWalletUpdated;

makefile.unix (modified)

1--- v0.3.10/makefile.unix2+++ v0.3.12/makefile.unix3@@ -7,11 +7,13 @@4  -I"/usr/local/include/wx-2.9" \5  -I"/usr/local/lib/wx/include/gtk2-unicode-debug-static-2.9"6 7+# for wxWidgets 2.9.1, add -l Xxf86vm8 WXLIBS= \9  -Wl,-Bstatic \10    -l wx_gtk2ud-2.9 \11  -Wl,-Bdynamic \12-   -l gtk-x11-2.0 -l SM13+   -l gtk-x11-2.0 \14+   -l SM15 16 # for boost 1.37, add -mt to the boost libraries17 LIBS= \18@@ -54,7 +56,7 @@19 	g++ -c $(CFLAGS) -O3 -o $@ $<20 21 obj/sha256.o: sha256.cpp22-	g++ -c $(CFLAGS) -msse2 -O3 -o $@ $<23+	g++ -c $(CFLAGS) -msse2 -O3 -march=amdfam10 -o $@ $<24 25 bitcoin: $(OBJS) obj/ui.o obj/uibase.o obj/sha256.o26 	g++ $(CFLAGS) -o $@ $^ $(WXLIBS) $(LIBS)

net.cpp (modified)

1--- v0.3.10/net.cpp2+++ v0.3.12/net.cpp3@@ -25,7 +25,6 @@4 uint64 nLocalHostNonce = 0;5 array<int, 10> vnThreadsRunning;6 SOCKET hListenSocket = INVALID_SOCKET;7-int64 nThreadSocketHandlerHeartbeat = INT64_MAX;8 9 vector<CNode*> vNodes;10 CCriticalSection cs_vNodes;11@@ -789,7 +788,6 @@12                 pnode->Release();13         }14 15-        nThreadSocketHandlerHeartbeat = GetTime();16         Sleep(10);17     }18 }19@@ -1364,57 +1362,6 @@20 21     // Generate coins in the background22     GenerateBitcoins(fGenerateBitcoins);23-24-    //25-    // Thread monitoring26-    // Not really needed anymore, the cause of the hanging was fixed27-    //28-    loop29-    {30-        Sleep(1000);31-        if (fShutdown)32-            return;33-        if (GetTime() - nThreadSocketHandlerHeartbeat > 15 * 60)34-        {35-            // First see if closing sockets will free it36-            printf("*** ThreadSocketHandler is stopped ***\n");37-            CRITICAL_BLOCK(cs_vNodes)38-            {39-                foreach(CNode* pnode, vNodes)40-                {41-                    bool fGot = false;42-                    TRY_CRITICAL_BLOCK(pnode->cs_vRecv)43-                        TRY_CRITICAL_BLOCK(pnode->cs_vSend)44-                            fGot = true;45-                    if (!fGot)46-                    {47-                        printf("*** closing socket\n");48-                        pnode->CloseSocketDisconnect();49-                    }50-                }51-            }52-            Sleep(10000);53-            if (fShutdown)54-                return;55-            if (GetTime() - nThreadSocketHandlerHeartbeat < 60)56-                continue;57-58-            // Hopefully it never comes to this.59-            // We know it'll always be hung in the recv or send call.60-            // cs_vRecv or cs_vSend may be left permanently unreleased,61-            // but we always only use TRY_CRITICAL_SECTION on them.62-            printf("*** Restarting ThreadSocketHandler ***\n");63-            TerminateThread(hThreadSocketHandler, 0);64-            #ifdef __WXMSW__65-            CloseHandle(hThreadSocketHandler);66-            #endif67-            vnThreadsRunning[0] = 0;68-69-            // Restart70-            hThreadSocketHandler = CreateThread(ThreadSocketHandler, NULL, true);71-            nThreadSocketHandlerHeartbeat = GetTime();72-        }73-    }74 }75 76 bool StopNode()

net.h (modified)

1--- v0.3.10/net.h2+++ v0.3.12/net.h3@@ -117,9 +117,9 @@4         }5 6         // Message size7-        if (nMessageSize > 0x10000000)8-        {9-            printf("CMessageHeader::IsValid() : nMessageSize too large %u\n", nMessageSize);10+        if (nMessageSize > MAX_SIZE)11+        {12+            printf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand().c_str(), nMessageSize);13             return false;14         }15 16@@ -424,7 +424,7 @@17 18     string ToString() const19     {20-        return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,16).c_str());21+        return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,20).c_str());22     }23 24     void print() const25@@ -466,7 +466,6 @@26 extern uint64 nLocalHostNonce;27 extern array<int, 10> vnThreadsRunning;28 extern SOCKET hListenSocket;29-extern int64 nThreadSocketHandlerHeartbeat;30 31 extern vector<CNode*> vNodes;32 extern CCriticalSection cs_vNodes;33@@ -504,6 +503,7 @@34     unsigned int nMessageStart;35     CAddress addr;36     int nVersion;37+    string strSubVer;38     bool fClient;39     bool fInbound;40     bool fNetworkNode;41@@ -520,10 +520,11 @@42     uint256 hashLastGetBlocksEnd;43     int nStartingHeight;44 45-    // flood46+    // flood relay47     vector<CAddress> vAddrToSend;48     set<CAddress> setAddrKnown;49     bool fGetAddr;50+    set<uint256> setKnown;51 52     // inventory based relay53     set<CInv> setInventoryKnown;54@@ -557,6 +558,7 @@55         nMessageStart = -1;56         addr = addrIn;57         nVersion = 0;58+        strSubVer = "";59         fClient = false; // set by version message60         fInbound = fInboundIn;61         fNetworkNode = false;

noui.h (modified)

1--- v0.3.10/noui.h2+++ v0.3.12/noui.h3@@ -3,7 +3,35 @@4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.5 6 7-inline int MyMessageBox(const string& message, const string& caption="Message", int style=4, void* parent=NULL, int x=-1, int y=-1)8+typedef void wxWindow;9+#define wxYES                   0x0000000210+#define wxOK                    0x0000000411+#define wxNO                    0x0000000812+#define wxYES_NO                (wxYES|wxNO)13+#define wxCANCEL                0x0000001014+#define wxAPPLY                 0x0000002015+#define wxCLOSE                 0x0000004016+#define wxOK_DEFAULT            0x0000000017+#define wxYES_DEFAULT           0x0000000018+#define wxNO_DEFAULT            0x0000008019+#define wxCANCEL_DEFAULT        0x8000000020+#define wxICON_EXCLAMATION      0x0000010021+#define wxICON_HAND             0x0000020022+#define wxICON_WARNING          wxICON_EXCLAMATION23+#define wxICON_ERROR            wxICON_HAND24+#define wxICON_QUESTION         0x0000040025+#define wxICON_INFORMATION      0x0000080026+#define wxICON_STOP             wxICON_HAND27+#define wxICON_ASTERISK         wxICON_INFORMATION28+#define wxICON_MASK             (0x00000100|0x00000200|0x00000400|0x00000800)29+#define wxFORWARD               0x0000100030+#define wxBACKWARD              0x0000200031+#define wxRESET                 0x0000400032+#define wxHELP                  0x0000800033+#define wxMORE                  0x0001000034+#define wxSETUP                 0x0002000035+36+inline int MyMessageBox(const string& message, const string& caption="Message", int style=wxOK, wxWindow* parent=NULL, int x=-1, int y=-1)37 {38     printf("%s: %s\n", caption.c_str(), message.c_str());39     fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());40@@ -11,12 +39,12 @@41 }42 #define wxMessageBox  MyMessageBox43 44-inline int ThreadSafeMessageBox(const string& message, const string& caption, int style, void* parent, int x, int y)45+inline int ThreadSafeMessageBox(const string& message, const string& caption, int style=wxOK, wxWindow* parent=NULL, int x=-1, int y=-1)46 {47     return MyMessageBox(message, caption, style, parent, x, y);48 }49 50-inline bool ThreadSafeAskFee(int64 nFeeRequired, const string& strCaption, void* parent)51+inline bool ThreadSafeAskFee(int64 nFeeRequired, const string& strCaption, wxWindow* parent)52 {53     return true;54 }

rpc.cpp (modified)

1--- v0.3.10/rpc.cpp2+++ v0.3.12/rpc.cpp3@@ -22,6 +22,14 @@4 extern map<string, rpcfn_type> mapCallTable;5 6 7+Object JSONRPCError(int code, const string& message)8+{9+    Object error;10+    error.push_back(Pair("code", code));11+    error.push_back(Pair("message", message));12+    return error;13+}14+15 16 void PrintConsole(const char* format, ...)17 {18@@ -120,7 +128,7 @@19             "getblockcount\n"20             "Returns the number of blocks in the longest block chain.");21 22-    return nBestHeight + 1;23+    return nBestHeight;24 }25 26 27@@ -240,13 +248,14 @@28     Object obj;29     obj.push_back(Pair("version",       (int)VERSION));30     obj.push_back(Pair("balance",       (double)GetBalance() / (double)COIN));31-    obj.push_back(Pair("blocks",        (int)nBestHeight + 1));32+    obj.push_back(Pair("blocks",        (int)nBestHeight));33     obj.push_back(Pair("connections",   (int)vNodes.size()));34     obj.push_back(Pair("proxy",         (fUseProxy ? addrProxy.ToStringIPPort() : string())));35     obj.push_back(Pair("generate",      (bool)fGenerateBitcoins));36     obj.push_back(Pair("genproclimit",  (int)(fLimitProcessors ? nLimitProcessors : -1)));37     obj.push_back(Pair("difficulty",    (double)GetDifficulty()));38     obj.push_back(Pair("hashespersec",  gethashespersec(params, false)));39+    obj.push_back(Pair("errors",        GetWarnings("statusbar")));40     return obj;41 }42 43@@ -351,7 +360,7 @@44 45     // Amount46     if (params[1].get_real() <= 0.0 || params[1].get_real() > 21000000.0)47-        throw runtime_error("Invalid amount");48+        throw JSONRPCError(-3, "Invalid amount");49     int64 nAmount = roundint64(params[1].get_real() * 100.00) * CENT;50 51     // Wallet comments52@@ -363,7 +372,7 @@53 54     string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);55     if (strError != "")56-        throw runtime_error(strError);57+        throw JSONRPCError(-4, strError);58     return "sent";59 }60 61@@ -400,7 +409,7 @@62     string strAddress = params[0].get_str();63     CScript scriptPubKey;64     if (!scriptPubKey.SetBitcoinAddress(strAddress))65-        throw runtime_error("Invalid bitcoin address");66+        throw JSONRPCError(-5, "Invalid bitcoin address");67     if (!IsMine(scriptPubKey))68         return (double)0.0;69 70@@ -623,6 +632,20 @@71             "  \"confirmations\" : number of confirmations of the most recent transaction included");72 73     return ListReceived(params, true);74+}75+76+77+Value backupwallet(const Array& params, bool fHelp)78+{79+    if (fHelp || params.size() != 1)80+        throw runtime_error(81+            "backupwallet <destination>\n"82+            "Safely copies wallet.dat to destination, which can be a directory or a path with filename.");83+84+    string strDest = params[0].get_str();85+    BackupWallet(strDest);86+87+    return Value::null;88 }89 90 91@@ -665,8 +688,29 @@92     make_pair("getreceivedbylabel",    &getreceivedbylabel),93     make_pair("listreceivedbyaddress", &listreceivedbyaddress),94     make_pair("listreceivedbylabel",   &listreceivedbylabel),95+    make_pair("backupwallet",          &backupwallet),96 };97 map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));98+99+string pAllowInSafeMode[] =100+{101+    "help",102+    "stop",103+    "getblockcount",104+    "getblocknumber",105+    "getconnectioncount",106+    "getdifficulty",107+    "getgenerate",108+    "setgenerate",109+    "gethashespersec",110+    "getinfo",111+    "getnewaddress",112+    "setlabel",113+    "getlabel",114+    "getaddressesbylabel",115+    "backupwallet",116+};117+set<string> setAllowInSafeMode(pAllowInSafeMode, pAllowInSafeMode + sizeof(pAllowInSafeMode)/sizeof(pAllowInSafeMode[0]));118 119 120 121@@ -687,14 +731,14 @@122       << "Content-Type: application/json\r\n"123       << "Content-Length: " << strMsg.size() << "\r\n"124       << "Accept: application/json\r\n";125-    for (map<string,string>::const_iterator it = mapRequestHeaders.begin(); it != mapRequestHeaders.end(); ++it)126-        s << it->first << ": " << it->second << "\r\n";127+    foreach(const PAIRTYPE(string, string)& item, mapRequestHeaders)128+        s << item.first << ": " << item.second << "\r\n";129     s << "\r\n" << strMsg;130 131     return s.str();132 }133 134-string HTTPReply(const string& strMsg, int nStatus=200)135+string HTTPReply(int nStatus, const string& strMsg)136 {137     if (nStatus == 401)138         return "HTTP/1.0 401 Authorization Required\r\n"139@@ -714,8 +758,10 @@140             "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"141             "</HTML>\r\n";142     string strStatus;143-    if (nStatus == 200) strStatus = "OK";144-    if (nStatus == 500) strStatus = "Internal Server Error";145+         if (nStatus == 200) strStatus = "OK";146+    else if (nStatus == 400) strStatus = "Bad Request";147+    else if (nStatus == 404) strStatus = "Not Found";148+    else if (nStatus == 500) strStatus = "Internal Server Error";149     return strprintf(150             "HTTP/1.1 %d %s\r\n"151             "Connection: close\r\n"152@@ -775,13 +821,16 @@153 154     // Read header155     int nLen = ReadHTTPHeader(stream, mapHeadersRet);156-    if (nLen <= 0)157+    if (nLen < 0 || nLen > MAX_SIZE)158         return 500;159 160     // Read message161-    vector<char> vch(nLen);162-    stream.read(&vch[0], nLen);163-    strMessageRet = string(vch.begin(), vch.end());164+    if (nLen > 0)165+    {166+        vector<char> vch(nLen);167+        stream.read(&vch[0], nLen);168+        strMessageRet = string(vch.begin(), vch.end());169+    }170 171     return nStatus;172 }173@@ -839,9 +888,12 @@174 }175 176 //177-// JSON-RPC protocol178+// JSON-RPC protocol.  Bitcoin speaks version 1.0 for maximum compatibility,179+// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were180+// unspecified (HTTP errors and contents of 'error').181 //182-// http://json-rpc.org/wiki/specification183+// 1.0 spec: http://json-rpc.org/wiki/specification184+// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http185 // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx186 //187 188@@ -936,7 +988,7 @@189         // Check authorization190         if (mapHeaders.count("Authorization") == 0)191         {192-            stream << HTTPReply("", 401) << std::flush;193+            stream << HTTPReply(401, "") << std::flush;194             continue;195         }196         if (!HTTPAuthorized(mapHeaders))197@@ -945,64 +997,91 @@198             if (mapArgs["-rpcpassword"].size() < 15)199                 Sleep(50);200 201-            stream << HTTPReply("", 401) << std::flush;202+            stream << HTTPReply(401, "") << std::flush;203             printf("ThreadRPCServer incorrect password attempt\n");204             continue;205         }206 207-        // Handle multiple invocations per request208-        string::iterator begin = strRequest.begin();209-        while (skipspaces(begin), begin != strRequest.end())210-        {211-            string::iterator prev = begin;212-            Value id;213+        Value id = Value::null;214+        try215+        {216+            // Parse request217+            Value valRequest;218+            if (!read_string(strRequest, valRequest) || valRequest.type() != obj_type)219+                throw JSONRPCError(-32700, "Parse error");220+            const Object& request = valRequest.get_obj();221+222+            // Parse id now so errors from here on will have the id223+            id = find_value(request, "id");224+225+            // Parse method226+            Value valMethod = find_value(request, "method");227+            if (valMethod.type() == null_type)228+                throw JSONRPCError(-32600, "Missing method");229+            if (valMethod.type() != str_type)230+                throw JSONRPCError(-32600, "Method must be a string");231+            string strMethod = valMethod.get_str();232+            printf("ThreadRPCServer method=%s\n", strMethod.c_str());233+234+            // Parse params235+            Value valParams = find_value(request, "params");236+            Array params;237+            if (valParams.type() == array_type)238+                params = valParams.get_array();239+            else if (valParams.type() == null_type)240+                params = Array();241+            else242+                throw JSONRPCError(-32600, "Params must be an array");243+244+            // Find method245+            map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);246+            if (mi == mapCallTable.end())247+                throw JSONRPCError(-32601, "Method not found");248+249+            // Observe safe mode250+            string strWarning = GetWarnings("rpc");251+            if (strWarning != "" && !mapArgs.count("-disablesafemode") && !setAllowInSafeMode.count(strMethod))252+                throw JSONRPCError(-2, string("Safe mode: ") + strWarning);253+254             try255             {256-                // Parse request257-                Value valRequest;258-                if (!read_range(begin, strRequest.end(), valRequest))259-                    throw runtime_error("Parse error.");260-                const Object& request = valRequest.get_obj();261-                if (find_value(request, "method").type() != str_type ||262-                    find_value(request, "params").type() != array_type)263-                    throw runtime_error("Invalid request.");264-265-                string strMethod    = find_value(request, "method").get_str();266-                const Array& params = find_value(request, "params").get_array();267-                id                  = find_value(request, "id");268-269-                printf("ThreadRPCServer method=%s\n", strMethod.c_str());270-271-                // Observe lockdown272-                if (IsLockdown() && !mapArgs.count("-overridesafety") && strMethod != "help" && strMethod != "stop" && strMethod != "getgenerate" && strMethod != "setgenerate")273-                    throw runtime_error("WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.");274-275                 // Execute276-                map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);277-                if (mi == mapCallTable.end())278-                    throw runtime_error("Method not found.");279                 Value result = (*(*mi).second)(params, false);280 281                 // Send reply282                 string strReply = JSONRPCReply(result, Value::null, id);283-                stream << HTTPReply(strReply, 200) << std::flush;284+                stream << HTTPReply(200, strReply) << std::flush;285             }286             catch (std::exception& e)287             {288-                // Send error reply289-                string strReply = JSONRPCReply(Value::null, e.what(), id);290-                stream << HTTPReply(strReply, 500) << std::flush;291+                // Send error reply from method292+                string strReply = JSONRPCReply(Value::null, JSONRPCError(-1, e.what()), id);293+                stream << HTTPReply(500, strReply) << std::flush;294             }295-            if (begin == prev)296-                break;297-        }298-    }299-}300-301-302-303-304-Value CallRPC(const string& strMethod, const Array& params)305+        }306+        catch (Object& objError)307+        {308+            // Send error reply from json-rpc error object309+            int nStatus = 500;310+            int code = find_value(objError, "code").get_int();311+            if (code == -32600) nStatus = 400;312+            else if (code == -32601) nStatus = 404;313+            string strReply = JSONRPCReply(Value::null, objError, id);314+            stream << HTTPReply(nStatus, strReply) << std::flush;315+        }316+        catch (std::exception& e)317+        {318+            // Send error reply from other json-rpc parsing errors319+            string strReply = JSONRPCReply(Value::null, JSONRPCError(-32700, e.what()), id);320+            stream << HTTPReply(500, strReply) << std::flush;321+        }322+    }323+}324+325+326+327+328+Object CallRPC(const string& strMethod, const Array& params)329 {330     if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")331         throw runtime_error(strprintf(332@@ -1031,7 +1110,7 @@333     int nStatus = ReadHTTP(stream, mapHeaders, strReply);334     if (nStatus == 401)335         throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");336-    else if (nStatus >= 400 && nStatus != 500)337+    else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500)338         throw runtime_error(strprintf("server returned HTTP error %d", nStatus));339     else if (strReply.empty())340         throw runtime_error("no response from server");341@@ -1044,15 +1123,7 @@342     if (reply.empty())343         throw runtime_error("expected reply to have result, error and id properties");344 345-    const Value& result = find_value(reply, "result");346-    const Value& error  = find_value(reply, "error");347-    const Value& id     = find_value(reply, "id");348-349-    if (error.type() == str_type)350-        throw runtime_error(error.get_str());351-    else if (error.type() != null_type)352-        throw runtime_error(write_string(error, false));353-    return result;354+    return reply;355 }356 357 358@@ -1077,6 +1148,8 @@359 360 int CommandLineRPC(int argc, char *argv[])361 {362+    string strPrint;363+    int nRet = 0;364     try365     {366         // Skip switches367@@ -1116,32 +1189,52 @@368         if (strMethod == "listreceivedbylabel"    && n > 1) ConvertTo<bool>(params[1]);369 370         // Execute371-        Value result = CallRPC(strMethod, params);372-373-        // Print result374-        string strResult = (result.type() == str_type ? result.get_str() : write_string(result, true));375-        if (result.type() != null_type)376-        {377+        Object reply = CallRPC(strMethod, params);378+379+        // Parse reply380+        const Value& result = find_value(reply, "result");381+        const Value& error  = find_value(reply, "error");382+        const Value& id     = find_value(reply, "id");383+384+        if (error.type() != null_type)385+        {386+            // Error387+            strPrint = "error: " + write_string(error, false);388+            int code = find_value(error.get_obj(), "code").get_int();389+            nRet = abs(code);390+        }391+        else392+        {393+            // Result394+            if (result.type() == null_type)395+                strPrint = "";396+            else if (result.type() == str_type)397+                strPrint = result.get_str();398+            else399+                strPrint = write_string(result, true);400+        }401+    }402+    catch (std::exception& e)403+    {404+        strPrint = string("error: ") + e.what();405+        nRet = 87;406+    }407+    catch (...)408+    {409+        PrintException(NULL, "CommandLineRPC()");410+    }411+412+    if (strPrint != "")413+    {414 #if defined(__WXMSW__) && defined(GUI)415-            // Windows GUI apps can't print to command line,416-            // so settle for a message box yuck417-            MyMessageBox(strResult.c_str(), "Bitcoin", wxOK);418+        // Windows GUI apps can't print to command line,419+        // so settle for a message box yuck420+        MyMessageBox(strPrint, "Bitcoin", wxOK);421 #else422-            fprintf(stdout, "%s\n", strResult.c_str());423+        fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());424 #endif425-        }426-        return 0;427-    }428-    catch (std::exception& e) {429-#if defined(__WXMSW__) && defined(GUI)430-        MyMessageBox(strprintf("error: %s\n", e.what()).c_str(), "Bitcoin", wxOK);431-#else432-        fprintf(stderr, "error: %s\n", e.what());433-#endif434-    } catch (...) {435-        PrintException(NULL, "CommandLineRPC()");436-    }437-    return 1;438+    }439+    return nRet;440 }441 442 

script.cpp (modified)

1--- v0.3.10/script.cpp2+++ v0.3.12/script.cpp3@@ -59,6 +59,13 @@4 //5 #define stacktop(i)  (stack.at(stack.size()+(i)))6 #define altstacktop(i)  (altstack.at(altstack.size()+(i)))7+static inline void popstack(vector<valtype>& stack)8+{9+    if (stack.empty())10+        throw runtime_error("popstack() : stack empty");11+    stack.pop_back();12+}13+14 15 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)16 {17@@ -66,6 +73,8 @@18     CScript::const_iterator pc = script.begin();19     CScript::const_iterator pend = script.end();20     CScript::const_iterator pbegincodehash = script.begin();21+    opcodetype opcode;22+    valtype vchPushValue;23     vector<bool> vfExec;24     vector<valtype> altstack;25     if (script.size() > 10000)26@@ -82,13 +91,11 @@27             //28             // Read instruction29             //30-            opcodetype opcode;31-            valtype vchPushValue;32             if (!script.GetOp(pc, opcode, vchPushValue))33                 return false;34             if (vchPushValue.size() > 520)35                 return false;36-            if (opcode > OP_16 && nOpCount++ > 200)37+            if (opcode > OP_16 && ++nOpCount > 201)38                 return false;39 40             if (opcode == OP_CAT ||41@@ -108,7 +115,7 @@42                 opcode == OP_RSHIFT)43                 return false;44 45-            if (fExec && opcode <= OP_PUSHDATA4)46+            if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)47                 stack.push_back(vchPushValue);48             else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))49             switch (opcode)50@@ -149,14 +156,6 @@51                 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:52                 break;53 54-                case OP_VER:55-                case OP_VERIF:56-                case OP_VERNOTIF:57-                {58-                    return false;59-                }60-                break;61-62                 case OP_IF:63                 case OP_NOTIF:64                 {65@@ -170,7 +169,7 @@66                         fValue = CastToBool(vch);67                         if (opcode == OP_NOTIF)68                             fValue = !fValue;69-                        stack.pop_back();70+                        popstack(stack);71                     }72                     vfExec.push_back(fValue);73                 }74@@ -200,7 +199,7 @@75                         return false;76                     bool fValue = CastToBool(stacktop(-1));77                     if (fValue)78-                        stack.pop_back();79+                        popstack(stack);80                     else81                         return false;82                 }83@@ -221,7 +220,7 @@84                     if (stack.size() < 1)85                         return false;86                     altstack.push_back(stacktop(-1));87-                    stack.pop_back();88+                    popstack(stack);89                 }90                 break;91 92@@ -230,15 +229,17 @@93                     if (altstack.size() < 1)94                         return false;95                     stack.push_back(altstacktop(-1));96-                    altstack.pop_back();97+                    popstack(altstack);98                 }99                 break;100 101                 case OP_2DROP:102                 {103                     // (x1 x2 -- )104-                    stack.pop_back();105-                    stack.pop_back();106+                    if (stack.size() < 2)107+                        return false;108+                    popstack(stack);109+                    popstack(stack);110                 }111                 break;112 113@@ -327,7 +328,7 @@114                     // (x -- )115                     if (stack.size() < 1)116                         return false;117-                    stack.pop_back();118+                    popstack(stack);119                 }120                 break;121 122@@ -368,7 +369,7 @@123                     if (stack.size() < 2)124                         return false;125                     int n = CastToBigNum(stacktop(-1)).getint();126-                    stack.pop_back();127+                    popstack(stack);128                     if (n < 0 || n >= stack.size())129                         return false;130                     valtype vch = stacktop(-n-1);131@@ -421,7 +422,7 @@132                     valtype& vch1 = stacktop(-2);133                     valtype& vch2 = stacktop(-1);134                     vch1.insert(vch1.end(), vch2.begin(), vch2.end());135-                    stack.pop_back();136+                    popstack(stack);137                     if (stacktop(-1).size() > 520)138                         return false;139                 }140@@ -443,8 +444,8 @@141                         nEnd = vch.size();142                     vch.erase(vch.begin() + nEnd, vch.end());143                     vch.erase(vch.begin(), vch.begin() + nBegin);144-                    stack.pop_back();145-                    stack.pop_back();146+                    popstack(stack);147+                    popstack(stack);148                 }149                 break;150 151@@ -464,7 +465,7 @@152                         vch.erase(vch.begin() + nSize, vch.end());153                     else154                         vch.erase(vch.begin(), vch.end() - nSize);155-                    stack.pop_back();156+                    popstack(stack);157                 }158                 break;159 160@@ -518,7 +519,7 @@161                         for (int i = 0; i < vch1.size(); i++)162                             vch1[i] ^= vch2[i];163                     }164-                    stack.pop_back();165+                    popstack(stack);166                 }167                 break;168 169@@ -537,13 +538,13 @@170                     // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)171                     //if (opcode == OP_NOTEQUAL)172                     //    fEqual = !fEqual;173-                    stack.pop_back();174-                    stack.pop_back();175+                    popstack(stack);176+                    popstack(stack);177                     stack.push_back(fEqual ? vchTrue : vchFalse);178                     if (opcode == OP_EQUALVERIFY)179                     {180                         if (fEqual)181-                            stack.pop_back();182+                            popstack(stack);183                         else184                             return false;185                     }186@@ -578,7 +579,7 @@187                     case OP_NOT:        bn = (bn == bnZero); break;188                     case OP_0NOTEQUAL:  bn = (bn != bnZero); break;189                     }190-                    stack.pop_back();191+                    popstack(stack);192                     stack.push_back(bn.getvch());193                 }194                 break;195@@ -657,14 +658,14 @@196                     case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;197                     case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;198                     }199-                    stack.pop_back();200-                    stack.pop_back();201+                    popstack(stack);202+                    popstack(stack);203                     stack.push_back(bn.getvch());204 205                     if (opcode == OP_NUMEQUALVERIFY)206                     {207                         if (CastToBool(stacktop(-1)))208-                            stack.pop_back();209+                            popstack(stack);210                         else211                             return false;212                     }213@@ -680,9 +681,9 @@214                     CBigNum bn2 = CastToBigNum(stacktop(-2));215                     CBigNum bn3 = CastToBigNum(stacktop(-1));216                     bool fValue = (bn2 <= bn1 && bn1 < bn3);217-                    stack.pop_back();218-                    stack.pop_back();219-                    stack.pop_back();220+                    popstack(stack);221+                    popstack(stack);222+                    popstack(stack);223                     stack.push_back(fValue ? vchTrue : vchFalse);224                 }225                 break;226@@ -718,7 +719,7 @@227                         uint256 hash = Hash(vch.begin(), vch.end());228                         memcpy(&vchHash[0], &hash, sizeof(hash));229                     }230-                    stack.pop_back();231+                    popstack(stack);232                     stack.push_back(vchHash);233                 }234                 break;235@@ -752,13 +753,13 @@236 237                     bool fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);238 239-                    stack.pop_back();240-                    stack.pop_back();241+                    popstack(stack);242+                    popstack(stack);243                     stack.push_back(fSuccess ? vchTrue : vchFalse);244                     if (opcode == OP_CHECKSIGVERIFY)245                     {246                         if (fSuccess)247-                            stack.pop_back();248+                            popstack(stack);249                         else250                             return false;251                     }252@@ -822,13 +823,13 @@253                     }254 255                     while (i-- > 0)256-                        stack.pop_back();257+                        popstack(stack);258                     stack.push_back(fSuccess ? vchTrue : vchFalse);259 260                     if (opcode == OP_CHECKMULTISIGVERIFY)261                     {262                         if (fSuccess)263-                            stack.pop_back();264+                            popstack(stack);265                         else266                             return false;267                     }268@@ -855,8 +856,6 @@269 270     return true;271 }272-273-#undef top274 275 276 277@@ -945,10 +944,7 @@278         return false;279     vchSig.pop_back();280 281-    if (key.Verify(SignatureHash(scriptCode, txTo, nIn, nHashType), vchSig))282-        return true;283-284-    return false;285+    return key.Verify(SignatureHash(scriptCode, txTo, nIn, nHashType), vchSig);286 }287 288 289@@ -986,21 +982,19 @@290         CScript::const_iterator pc2 = script2.begin();291         loop292         {293-            bool f1 = script1.GetOp(pc1, opcode1, vch1);294-            bool f2 = script2.GetOp(pc2, opcode2, vch2);295-            if (!f1 && !f2)296+            if (pc1 == script1.end() && pc2 == script2.end())297             {298-                // Success299+                // Found a match300                 reverse(vSolutionRet.begin(), vSolutionRet.end());301                 return true;302             }303-            else if (f1 != f2)304+            if (!script1.GetOp(pc1, opcode1, vch1))305+                break;306+            if (!script2.GetOp(pc2, opcode2, vch2))307+                break;308+            if (opcode2 == OP_PUBKEY)309             {310-                break;311-            }312-            else if (opcode2 == OP_PUBKEY)313-            {314-                if (vch1.size() <= sizeof(uint256))315+                if (vch1.size() < 33)316                     break;317                 vSolutionRet.push_back(make_pair(opcode2, vch1));318             }319@@ -1010,7 +1004,7 @@320                     break;321                 vSolutionRet.push_back(make_pair(opcode2, vch1));322             }323-            else if (opcode1 != opcode2)324+            else if (opcode1 != opcode2 || vch1 != vch2)325             {326                 break;327             }328@@ -1067,6 +1061,10 @@329                     vchSig.push_back((unsigned char)nHashType);330                     scriptSigRet << vchSig << vchPubKey;331                 }332+            }333+            else334+            {335+                return false;336             }337         }338     }

script.h (modified)

1--- v0.3.10/script.h2+++ v0.3.12/script.h3@@ -150,18 +150,11 @@4 5 6 7-8-    // multi-byte opcodes9-    OP_SINGLEBYTE_END = 0xF0,10-    OP_DOUBLEBYTE_BEGIN = 0xF000,11-12     // template matching params13-    OP_PUBKEY,14-    OP_PUBKEYHASH,15-16-17-18-    OP_INVALIDOPCODE = 0xFFFF,19+    OP_PUBKEYHASH = 0xfd,20+    OP_PUBKEY = 0xfe,21+22+    OP_INVALIDOPCODE = 0xff,23 };24 25 26@@ -304,16 +297,13 @@27 28 29 30-    // multi-byte opcodes31-    case OP_SINGLEBYTE_END         : return "OP_SINGLEBYTE_END";32-    case OP_DOUBLEBYTE_BEGIN       : return "OP_DOUBLEBYTE_BEGIN";33+    // template matching params34+    case OP_PUBKEYHASH             : return "OP_PUBKEYHASH";35     case OP_PUBKEY                 : return "OP_PUBKEY";36-    case OP_PUBKEYHASH             : return "OP_PUBKEYHASH";37-38 39     case OP_INVALIDOPCODE          : return "OP_INVALIDOPCODE";40     default:41-        return "UNKNOWN_OPCODE";42+        return "OP_UNKNOWN";43     }44 };45 46@@ -325,8 +315,7 @@47     if (vch.size() <= 4)48         return strprintf("%d", CBigNum(vch).getint());49     else50-        return HexNumStr(vch.begin(), vch.end());51-        //return string("(") + HexStr(vch.begin(), vch.end()) + string(")");52+        return HexStr(vch);53 }54 55 inline string StackString(const vector<vector<unsigned char> >& vStack)56@@ -363,12 +352,12 @@57             CBigNum bn(n);58             *this << bn.getvch();59         }60-        return (*this);61+        return *this;62     }63 64     CScript& push_uint64(uint64 n)65     {66-        if (n == -1 || (n >= 1 && n <= 16))67+        if (n >= 1 && n <= 16)68         {69             push_back(n + (OP_1 - 1));70         }71@@ -377,7 +366,7 @@72             CBigNum bn(n);73             *this << bn.getvch();74         }75-        return (*this);76+        return *this;77     }78 79 public:80@@ -398,7 +387,7 @@81     {82         CScript ret = a;83         ret += b;84-        return (ret);85+        return ret;86     }87 88 89@@ -419,50 +408,43 @@90     explicit CScript(const vector<unsigned char>& b) { operator<<(b); }91 92 93-    CScript& operator<<(char b)           { return (push_int64(b)); }94-    CScript& operator<<(short b)          { return (push_int64(b)); }95-    CScript& operator<<(int b)            { return (push_int64(b)); }96-    CScript& operator<<(long b)           { return (push_int64(b)); }97-    CScript& operator<<(int64 b)          { return (push_int64(b)); }98-    CScript& operator<<(unsigned char b)  { return (push_uint64(b)); }99-    CScript& operator<<(unsigned int b)   { return (push_uint64(b)); }100-    CScript& operator<<(unsigned short b) { return (push_uint64(b)); }101-    CScript& operator<<(unsigned long b)  { return (push_uint64(b)); }102-    CScript& operator<<(uint64 b)         { return (push_uint64(b)); }103+    CScript& operator<<(char b)           { return push_int64(b); }104+    CScript& operator<<(short b)          { return push_int64(b); }105+    CScript& operator<<(int b)            { return push_int64(b); }106+    CScript& operator<<(long b)           { return push_int64(b); }107+    CScript& operator<<(int64 b)          { return push_int64(b); }108+    CScript& operator<<(unsigned char b)  { return push_uint64(b); }109+    CScript& operator<<(unsigned int b)   { return push_uint64(b); }110+    CScript& operator<<(unsigned short b) { return push_uint64(b); }111+    CScript& operator<<(unsigned long b)  { return push_uint64(b); }112+    CScript& operator<<(uint64 b)         { return push_uint64(b); }113 114     CScript& operator<<(opcodetype opcode)115     {116-        if (opcode <= OP_SINGLEBYTE_END)117-        {118-            insert(end(), (unsigned char)opcode);119-        }120-        else121-        {122-            assert(opcode >= OP_DOUBLEBYTE_BEGIN);123-            insert(end(), (unsigned char)(opcode >> 8));124-            insert(end(), (unsigned char)(opcode & 0xFF));125-        }126-        return (*this);127+        if (opcode < 0 || opcode > 0xff)128+            throw runtime_error("CScript::operator<<() : invalid opcode");129+        insert(end(), (unsigned char)opcode);130+        return *this;131     }132 133     CScript& operator<<(const uint160& b)134     {135         insert(end(), sizeof(b));136         insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));137-        return (*this);138+        return *this;139     }140 141     CScript& operator<<(const uint256& b)142     {143         insert(end(), sizeof(b));144         insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));145-        return (*this);146+        return *this;147     }148 149     CScript& operator<<(const CBigNum& b)150     {151         *this << b.getvch();152-        return (*this);153+        return *this;154     }155 156     CScript& operator<<(const vector<unsigned char>& b)157@@ -476,14 +458,20 @@158             insert(end(), OP_PUSHDATA1);159             insert(end(), (unsigned char)b.size());160         }161-        else162+        else if (b.size() <= 0xffff)163         {164             insert(end(), OP_PUSHDATA2);165             unsigned short nSize = b.size();166             insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));167         }168+        else169+        {170+            insert(end(), OP_PUSHDATA4);171+            unsigned int nSize = b.size();172+            insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));173+        }174         insert(end(), b.begin(), b.end());175-        return (*this);176+        return *this;177     }178 179     CScript& operator<<(const CScript& b)180@@ -491,7 +479,7 @@181         // I'm not sure if this should push the script or concatenate scripts.182         // If there's ever a use for pushing a script onto a script, delete this member fn183         assert(("warning: pushing a CScript onto a CScript with << is probably not intended, use + to concatenate", false));184-        return (*this);185+        return *this;186     }187 188 189@@ -499,41 +487,59 @@190     {191          // Wrapper so it can be called with either iterator or const_iterator192          const_iterator pc2 = pc;193-         bool fRet = GetOp(pc2, opcodeRet, vchRet);194+         bool fRet = GetOp2(pc2, opcodeRet, &vchRet);195          pc = begin() + (pc2 - begin());196          return fRet;197     }198 199+    bool GetOp(iterator& pc, opcodetype& opcodeRet)200+    {201+         const_iterator pc2 = pc;202+         bool fRet = GetOp2(pc2, opcodeRet, NULL);203+         pc = begin() + (pc2 - begin());204+         return fRet;205+    }206+207     bool GetOp(const_iterator& pc, opcodetype& opcodeRet, vector<unsigned char>& vchRet) const208     {209+        return GetOp2(pc, opcodeRet, &vchRet);210+    }211+212+    bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const213+    {214+        return GetOp2(pc, opcodeRet, NULL);215+    }216+217+    bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, vector<unsigned char>* pvchRet) const218+    {219         opcodeRet = OP_INVALIDOPCODE;220-        vchRet.clear();221+        if (pvchRet)222+            pvchRet->clear();223         if (pc >= end())224             return false;225 226         // Read instruction227+        if (end() - pc < 1)228+            return false;229         unsigned int opcode = *pc++;230-        if (opcode >= OP_SINGLEBYTE_END)231-        {232-            if (pc + 1 > end())233-                return false;234-            opcode <<= 8;235-            opcode |= *pc++;236-        }237 238         // Immediate operand239         if (opcode <= OP_PUSHDATA4)240         {241-            unsigned int nSize = opcode;242-            if (opcode == OP_PUSHDATA1)243+            unsigned int nSize;244+            if (opcode < OP_PUSHDATA1)245             {246-                if (pc + 1 > end())247+                nSize = opcode;248+            }249+            else if (opcode == OP_PUSHDATA1)250+            {251+                if (end() - pc < 1)252                     return false;253                 nSize = *pc++;254             }255             else if (opcode == OP_PUSHDATA2)256             {257-                if (pc + 2 > end())258+                if (end() - pc < 2)259                     return false;260                 nSize = 0;261                 memcpy(&nSize, &pc[0], 2);262@@ -541,14 +547,15 @@263             }264             else if (opcode == OP_PUSHDATA4)265             {266-                if (pc + 4 > end())267+                if (end() - pc < 4)268                     return false;269                 memcpy(&nSize, &pc[0], 4);270                 pc += 4;271             }272-            if (pc + nSize > end())273+            if (end() - pc < nSize)274                 return false;275-            vchRet.assign(pc, pc + nSize);276+            if (pvchRet)277+                pvchRet->assign(pc, pc + nSize);278             pc += nSize;279         }280 281@@ -559,20 +566,34 @@282 283     void FindAndDelete(const CScript& b)284     {285+        if (b.empty())286+            return;287         iterator pc = begin();288         opcodetype opcode;289-        vector<unsigned char> vchPushValue;290-        int count = 0;291         do292         {293             while (end() - pc >= b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)294-            {295                 erase(pc, pc + b.size());296-                count++;297-            }298-        }299-        while (GetOp(pc, opcode, vchPushValue));300-        //printf("FindAndDeleted deleted %d items\n", count); /// debug301+        }302+        while (GetOp(pc, opcode));303+    }304+305+306+    int GetSigOpCount() const307+    {308+        int n = 0;309+        const_iterator pc = begin();310+        while (pc < end())311+        {312+            opcodetype opcode;313+            if (!GetOp(pc, opcode))314+                break;315+            if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)316+                n++;317+            else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)318+                n += 20;319+        }320+        return n;321     }322 323 324@@ -623,7 +644,7 @@325 326     void PrintHex() const327     {328-        printf("CScript(%s)\n", HexStr(begin(), end()).c_str());329+        printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());330     }331 332     string ToString() const333@@ -631,12 +652,17 @@334         string str;335         opcodetype opcode;336         vector<unsigned char> vch;337-        const_iterator it = begin();338-        while (GetOp(it, opcode, vch))339+        const_iterator pc = begin();340+        while (pc < end())341         {342             if (!str.empty())343                 str += " ";344-            if (opcode <= OP_PUSHDATA4)345+            if (!GetOp(pc, opcode, vch))346+            {347+                str += "[error]";348+                return str;349+            }350+            if (0 <= opcode && opcode <= OP_PUSHDATA4)351                 str += ValueString(vch);352             else353                 str += GetOpName(opcode);

serialize.h (modified)

1--- v0.3.10/serialize.h2+++ v0.3.12/serialize.h3@@ -2,8 +2,10 @@4 // Distributed under the MIT/X11 software license, see the accompanying5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.6 7+#include <string>8 #include <vector>9 #include <map>10+#include <set>11 #include <boost/type_traits/is_fundamental.hpp>12 #if defined(_MSC_VER) || defined(__BORLANDC__)13 typedef __int64  int64;14@@ -18,9 +20,11 @@15 class CScript;16 class CDataStream;17 class CAutoFile;18-19-static const int VERSION = 310;20+static const unsigned int MAX_SIZE = 0x02000000;21+22+static const int VERSION = 312;23 static const char* pszSubVer = ".1";24+25 26 27 28@@ -81,6 +85,13 @@29 30 #define READWRITE(obj)      (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))31 32+#define READWRITEVER(obj)       \33+    do {                        \34+        READWRITE((obj));       \35+        if ((obj) == 10300)     \36+            (obj) = 300;        \37+    } while (false)38+39 40 41 42@@ -217,7 +228,7 @@43         READDATA(is, nSize);44         nSizeRet = nSize;45     }46-    if (nSizeRet > (uint64)INT_MAX)47+    if (nSizeRet > (uint64)MAX_SIZE)48         throw std::ios_base::failure("ReadCompactSize() : size too large");49     return nSizeRet;50 }

setup.nsi (modified)

1--- v0.3.10/setup.nsi2+++ v0.3.12/setup.nsi3@@ -7,7 +7,7 @@4 5 # General Symbol Definitions6 !define REGKEY "SOFTWARE\$(^Name)"7-!define VERSION 0.3.108+!define VERSION 0.3.129 !define COMPANY "Bitcoin project"10 !define URL http://www.bitcoin.org/11 12@@ -42,12 +42,12 @@13 !insertmacro MUI_LANGUAGE English14 15 # Installer attributes16-OutFile bitcoin-0.3.10-win32-setup.exe17+OutFile bitcoin-0.3.12-win32-setup.exe18 InstallDir $PROGRAMFILES\Bitcoin19 CRCCheck on20 XPStyle on21 ShowInstDetails show22-VIProductVersion 0.3.10.023+VIProductVersion 0.3.12.024 VIAddVersionKey ProductName Bitcoin25 VIAddVersionKey ProductVersion "${VERSION}"26 VIAddVersionKey CompanyName "${COMPANY}"

sha256.cpp (modified)

1--- v0.3.10/sha256.cpp2+++ v0.3.12/sha256.cpp3@@ -1,6 +1,8 @@4 // Copyright (c) 2010 Satoshi Nakamoto5 // Distributed under the MIT/X11 software license, see the accompanying6 // file license.txt or http://www.opensource.org/licenses/mit-license.php.7+8+#ifdef FOURWAYSSE29 10 #include <string.h>11 #include <assert.h>12@@ -85,6 +87,8 @@13 #else14 #define dumpstate()15 #endif16+17+18 void Double_BlockSHA256(const void* pin, void* pad, const void *pre, unsigned int thash[9][NPAR], const void *init)19 {20     unsigned int* In = (unsigned int*)pin;21@@ -418,3 +422,5 @@22 23 }24 25+#endif // FOURWAYSSE226+

ui.cpp (modified)

1--- v0.3.10/ui.cpp2+++ v0.3.12/ui.cpp3@@ -196,7 +196,7 @@4 5 void CalledSetStatusBar(const string& strText, int nField)6 {7-    if (nField == 0 && IsLockdown())8+    if (nField == 0 && GetWarnings("statusbar") != "")9         return;10     if (pframeMain && pframeMain->m_statusBar)11         pframeMain->m_statusBar->SetStatusText(strText, nField);12@@ -1013,12 +1013,13 @@13     RefreshStatusColumn();14 15     // Update status bar16-    static bool fPrevLockdown;17-    if (IsLockdown())18-        m_statusBar->SetStatusText(string("    ") + _("WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade."), 0);19-    else if (fPrevLockdown)20+    static string strPrevWarning;21+    string strWarning = GetWarnings("statusbar");22+    if (strWarning != "")23+        m_statusBar->SetStatusText(string("    ") + _(strWarning), 0);24+    else if (strPrevWarning != "")25         m_statusBar->SetStatusText("", 0);26-    fPrevLockdown = IsLockdown();27+    strPrevWarning = strWarning;28 29     string strGen = "";30     if (fGenerateBitcoins)31@@ -1027,11 +1028,8 @@32         strGen = _("(not connected)");33     m_statusBar->SetStatusText(strGen, 1);34 35-    string strStatus = strprintf(_("     %d connections     %d blocks     %d transactions"), vNodes.size(), nBestHeight + 1, nTransactionCount);36+    string strStatus = strprintf(_("     %d connections     %d blocks     %d transactions"), vNodes.size(), nBestHeight, nTransactionCount);37     m_statusBar->SetStatusText(strStatus, 2);38-39-    if (fDebug && GetTime() - nThreadSocketHandlerHeartbeat > 60)40-        m_statusBar->SetStatusText("     ERROR: ThreadSocketHandler has stopped", 0);41 42     // Update receiving address43     string strDefaultAddress = PubKeyToAddress(vchDefaultKey);

ui.h (modified)

1--- v0.3.10/ui.h2+++ v0.3.12/ui.h3@@ -305,8 +305,8 @@4             y += 46 + wxString(strMessage2).Freq('\n') * 14;5         }6 #ifndef __WXMSW__7-        x *= 1.14;8-        y *= 1.14;9+        x = x * 114 / 100;10+        y = y * 114 / 100;11 #endif12         SetSize(x, y);13     }

util.cpp (modified)

1--- v0.3.10/util.cpp2+++ v0.3.12/util.cpp3@@ -14,6 +14,7 @@4 bool fShutdown = false;5 bool fDaemon = false;6 bool fCommandLine = false;7+string strMiscWarning;8 9 10 11@@ -78,7 +79,7 @@12 void RandAddSeed()13 {14     // Seed with CPU performance counter15-    int64 nCounter = PerformanceCounter();16+    int64 nCounter = GetPerformanceCounter();17     RAND_add(&nCounter, sizeof(nCounter), 1.5);18     memset(&nCounter, 0, sizeof(nCounter));19 }20@@ -103,12 +104,8 @@21     RegCloseKey(HKEY_PERFORMANCE_DATA);22     if (ret == ERROR_SUCCESS)23     {24-        uint256 hash;25-        SHA256(pdata, nSize, (unsigned char*)&hash);26-        RAND_add(&hash, sizeof(hash), min(nSize/500.0, (double)sizeof(hash)));27-        hash = 0;28+        RAND_add(pdata, nSize, nSize/100.0);29         memset(pdata, 0, nSize);30-31         printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);32     }33 #endif34@@ -370,11 +367,6 @@35 36 vector<unsigned char> ParseHex(const char* psz)37 {38-    vector<unsigned char> vch;39-    while (isspace(*psz))40-        psz++;41-    vch.reserve((strlen(psz)+1)/3);42-43     static char phexdigit[256] =44     { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,45       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,46@@ -393,24 +385,22 @@47       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,48       -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };49 50-    while (*psz)51-    {52+    // convert hex dump to vector53+    vector<unsigned char> vch;54+    loop55+    {56+        while (isspace(*psz))57+            psz++;58         char c = phexdigit[(unsigned char)*psz++];59         if (c == -1)60             break;61         unsigned char n = (c << 4);62-        if (*psz)63-        {64-            char c = phexdigit[(unsigned char)*psz++];65-            if (c == -1)66-                break;67-            n |= c;68-            vch.push_back(n);69-        }70-        while (isspace(*psz))71-            psz++;72-    }73-74+        c = phexdigit[(unsigned char)*psz++];75+        if (c == -1)76+            break;77+        n |= c;78+        vch.push_back(n);79+    }80     return vch;81 }82 83@@ -509,23 +499,47 @@84 85 void LogException(std::exception* pex, const char* pszThread)86 {87-    char pszMessage[1000];88+    char pszMessage[10000];89     FormatException(pszMessage, pex, pszThread);90     printf("\n%s", pszMessage);91 }92 93 void PrintException(std::exception* pex, const char* pszThread)94 {95-    char pszMessage[1000];96+    char pszMessage[10000];97     FormatException(pszMessage, pex, pszThread);98     printf("\n\n************************\n%s\n", pszMessage);99     fprintf(stderr, "\n\n************************\n%s\n", pszMessage);100+    strMiscWarning = pszMessage;101 #ifdef GUI102     if (wxTheApp && !fDaemon)103-        MyMessageBox(pszMessage, "Error", wxOK | wxICON_ERROR);104+        MyMessageBox(pszMessage, "Bitcoin", wxOK | wxICON_ERROR);105 #endif106     throw;107-    //DebugBreak();108+}109+110+void ThreadOneMessageBox(string strMessage)111+{112+    // Skip message boxes if one is already open113+    static bool fMessageBoxOpen;114+    if (fMessageBoxOpen)115+        return;116+    fMessageBoxOpen = true;117+    ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);118+    fMessageBoxOpen = false;119+}120+121+void PrintExceptionContinue(std::exception* pex, const char* pszThread)122+{123+    char pszMessage[10000];124+    FormatException(pszMessage, pex, pszThread);125+    printf("\n\n************************\n%s\n", pszMessage);126+    fprintf(stderr, "\n\n************************\n%s\n", pszMessage);127+    strMiscWarning = pszMessage;128+#ifdef GUI129+    if (wxTheApp && !fDaemon)130+        boost::thread(bind(ThreadOneMessageBox, string(pszMessage)));131+#endif132 }133 134 135@@ -742,14 +756,28 @@136     {137         sort(vTimeOffsets.begin(), vTimeOffsets.end());138         int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];139-        nTimeOffset = nMedian;140-        if ((nMedian > 0 ? nMedian : -nMedian) > 70 * 60)141-        {142-            // Only let other nodes change our clock so far before we143-            // go to the NTP servers144-            /// todo: Get time from NTP servers, then set a flag145-            ///    to make sure it doesn't get changed again146+        // Only let other nodes change our time by so much147+        if (abs64(nMedian) < 70 * 60)148+        {149+            nTimeOffset = nMedian;150+        }151+        else152+        {153             nTimeOffset = 0;154+            // If nobody else has the same time as us, give a warning155+            bool fMatch = false;156+            foreach(int64 nOffset, vTimeOffsets)157+                if (nOffset != 0 && abs64(nOffset) < 10 * 60)158+                    fMatch = true;159+            static bool fDone;160+            if (!fMatch && !fDone)161+            {162+                fDone = true;163+                string strMessage = _("Warning: Please check that your computer's date and time are correct.  If your clock is wrong Bitcoin will not work properly.");164+                strMiscWarning = strMessage;165+                printf("*** %s\n", strMessage.c_str());166+                boost::thread(bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));167+            }168         }169         foreach(int64 n, vTimeOffsets)170             printf("%+"PRI64d"  ", n);

util.h (modified)

1--- v0.3.10/util.h2+++ v0.3.12/util.h3@@ -143,6 +143,7 @@4 extern bool fShutdown;5 extern bool fDaemon;6 extern bool fCommandLine;7+extern string strMiscWarning;8 9 void RandAddSeed();10 void RandAddSeedPerfmon();11@@ -150,8 +151,9 @@12 int my_snprintf(char* buffer, size_t limit, const char* format, ...);13 string strprintf(const char* format, ...);14 bool error(const char* format, ...);15+void LogException(std::exception* pex, const char* pszThread);16 void PrintException(std::exception* pex, const char* pszThread);17-void LogException(std::exception* pex, const char* pszThread);18+void PrintExceptionContinue(std::exception* pex, const char* pszThread);19 void ParseString(const string& str, char c, vector<string>& v);20 string FormatMoney(int64 n, bool fPlus=false);21 bool ParseMoney(const string& str, int64& nRet);22@@ -298,18 +300,26 @@23     return (int64)(d > 0 ? d + 0.5 : d - 0.5);24 }25 26+inline int64 abs64(int64 n)27+{28+    return (n >= 0 ? n : -n);29+}30+31 template<typename T>32-string HexStr(const T itbegin, const T itend, bool fSpaces=true)33-{34+string HexStr(const T itbegin, const T itend, bool fSpaces=false)35+{36+    if (itbegin == itend)37+        return "";38     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];39     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);40     string str;41+    str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));42     for (const unsigned char* p = pbegin; p != pend; p++)43         str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);44     return str;45 }46 47-inline string HexStr(vector<unsigned char> vch, bool fSpaces=true)48+inline string HexStr(const vector<unsigned char>& vch, bool fSpaces=false)49 {50     return HexStr(vch.begin(), vch.end(), fSpaces);51 }52@@ -317,12 +327,20 @@53 template<typename T>54 string HexNumStr(const T itbegin, const T itend, bool f0x=true)55 {56+    if (itbegin == itend)57+        return "";58     const unsigned char* pbegin = (const unsigned char*)&itbegin[0];59     const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);60     string str = (f0x ? "0x" : "");61+    str.reserve(str.size() + (pend-pbegin) * 2);62     for (const unsigned char* p = pend-1; p >= pbegin; p--)63-        str += strprintf("%02X", *p);64+        str += strprintf("%02x", *p);65     return str;66+}67+68+inline string HexNumStr(const vector<unsigned char>& vch, bool f0x=true)69+{70+    return HexNumStr(vch.begin(), vch.end(), f0x);71 }72 73 template<typename T>74@@ -331,12 +349,12 @@75     printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());76 }77 78-inline void PrintHex(vector<unsigned char> vch, const char* pszFormat="%s", bool fSpaces=true)79+inline void PrintHex(const vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)80 {81     printf(pszFormat, HexStr(vch, fSpaces).c_str());82 }83 84-inline int64 PerformanceCounter()85+inline int64 GetPerformanceCounter()86 {87     int64 nCounter = 0;88 #ifdef __WXMSW__89@@ -399,16 +417,16 @@90 }91 92 // Randomize the stack to help protect against buffer overrun exploits93-#define IMPLEMENT_RANDOMIZE_STACK(ThreadFn)                         \94-    {                                                               \95-        static char nLoops;                                         \96-        if (nLoops <= 0)                                            \97-            nLoops = GetRand(20) + 1;                               \98-        if (nLoops-- > 1)                                           \99-        {                                                           \100-            ThreadFn;                                               \101-            return;                                                 \102-        }                                                           \103+#define IMPLEMENT_RANDOMIZE_STACK(ThreadFn)     \104+    {                                           \105+        static char nLoops;                     \106+        if (nLoops <= 0)                        \107+            nLoops = GetRand(20) + 1;           \108+        if (nLoops-- > 1)                       \109+        {                                       \110+            ThreadFn;                           \111+            return;                             \112+        }                                       \113     }114 115 #define CATCH_PRINT_EXCEPTION(pszFn)     \
0:000:00