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.13 → v0.3.14

20 files · +644 · −234 · 2ce73dbe8 · 2010-10-21 · s_nakamoto

Release commit message: -- version 0.3.14 release

Previous diff: v0.3.12 → v0.3.13. Next: v0.3.14 → v0.3.15.

base58.h (modified)

1--- v0.3.13/base58.h2+++ v0.3.14/base58.h3@@ -152,7 +152,7 @@4 5 6 7-static const unsigned char ADDRESSVERSION = 0;8+#define ADDRESSVERSION   ((unsigned char)(fTestNet ? 111 : 0))9 10 inline string Hash160ToAddress(uint160 hash160)11 {

build-msw.txt (modified)

1--- v0.3.13/build-msw.txt2+++ v0.3.14/build-msw.txt3@@ -12,12 +12,8 @@4 Compilers Supported5 -------------------6 MinGW GCC (recommended)7-8-MSVC 6.0 SP6: You'll need Boost version 1.34 because they dropped support9-for MSVC 6.0 after that.  However, they didn't add Asio until 1.35.10-You should still be able to build with MSVC 6.0 by adding Asio to 1.34 by11-unpacking boost_asio_*.zip into the boost directory:12-http://sourceforge.net/projects/asio/files/asio13+http://tdm-gcc.tdragon.net/ has an easy installer.  Go back a few versions14+for a little older gcc like gcc 4.4.?.15 16 MSVC 8.0 (2005) SP1 has been tested.  Note: MSVC 7.0 and up have a habit of17 linking to runtime DLLs that are not installed on XP by default.

db.cpp (modified)

1--- v0.3.13/db.cpp2+++ v0.3.14/db.cpp3@@ -576,6 +576,9 @@4 // CWalletDB5 //6 7+static set<int64> setKeyPool;8+static CCriticalSection cs_setKeyPool;9+10 bool CWalletDB::LoadWallet()11 {12     vchDefaultKey.clear();13@@ -653,6 +656,12 @@14             else if (strType == "defaultkey")15             {16                 ssValue >> vchDefaultKey;17+            }18+            else if (strType == "pool")19+            {20+                int64 nIndex;21+                ssKey >> nIndex;22+                setKeyPool.insert(nIndex);23             }24             else if (strType == "version")25             {26@@ -837,3 +846,66 @@27     }28 }29 30+31+void CWalletDB::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)32+{33+    nIndex = -1;34+    keypool.vchPubKey.clear();35+    CRITICAL_BLOCK(cs_main)36+    CRITICAL_BLOCK(cs_mapWallet)37+    CRITICAL_BLOCK(cs_setKeyPool)38+    {39+        // Top up key pool40+        int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);41+        while (setKeyPool.size() < nTargetSize+1)42+        {43+            int64 nEnd = 1;44+            if (!setKeyPool.empty())45+                nEnd = *(--setKeyPool.end()) + 1;46+            if (!Write(make_pair(string("pool"), nEnd), CKeyPool(GenerateNewKey())))47+                throw runtime_error("ReserveKeyFromKeyPool() : writing generated key failed");48+            setKeyPool.insert(nEnd);49+            printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());50+        }51+52+        // Get the oldest key53+        assert(!setKeyPool.empty());54+        nIndex = *(setKeyPool.begin());55+        setKeyPool.erase(setKeyPool.begin());56+        if (!Read(make_pair(string("pool"), nIndex), keypool))57+            throw runtime_error("ReserveKeyFromKeyPool() : read failed");58+        if (!mapKeys.count(keypool.vchPubKey))59+            throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");60+        assert(!keypool.vchPubKey.empty());61+        printf("keypool reserve %"PRI64d"\n", nIndex);62+    }63+}64+65+void CWalletDB::KeepKey(int64 nIndex)66+{67+    // Remove from key pool68+    CRITICAL_BLOCK(cs_main)69+    CRITICAL_BLOCK(cs_mapWallet)70+    {71+        Erase(make_pair(string("pool"), nIndex));72+    }73+    printf("keypool keep %"PRI64d"\n", nIndex);74+}75+76+void CWalletDB::ReturnKey(int64 nIndex)77+{78+    // Return to key pool79+    CRITICAL_BLOCK(cs_setKeyPool)80+        setKeyPool.insert(nIndex);81+    printf("keypool return %"PRI64d"\n", nIndex);82+}83+84+vector<unsigned char> CWalletDB::GetKeyFromKeyPool()85+{86+    int64 nIndex = 0;87+    CKeyPool keypool;88+    ReserveKeyFromKeyPool(nIndex, keypool);89+    KeepKey(nIndex);90+    return keypool.vchPubKey;91+}92+

db.h (modified)

1--- v0.3.13/db.h2+++ v0.3.14/db.h3@@ -308,6 +308,35 @@4 5 6 7+class CKeyPool8+{9+public:10+    int64 nTime;11+    vector<unsigned char> vchPubKey;12+13+    CKeyPool()14+    {15+        nTime = GetTime();16+    }17+18+    CKeyPool(const vector<unsigned char>& vchPubKeyIn)19+    {20+        nTime = GetTime();21+        vchPubKey = vchPubKeyIn;22+    }23+24+    IMPLEMENT_SERIALIZE25+    (26+        if (!(nType & SER_GETHASH))27+            READWRITE(nVersion);28+        READWRITE(nTime);29+        READWRITE(vchPubKey);30+    )31+};32+33+34+35+36 class CWalletDB : public CDB37 {38 public:39@@ -396,6 +425,13 @@40     }41 42     bool LoadWallet();43+protected:44+    void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);45+    void KeepKey(int64 nIndex);46+    static void ReturnKey(int64 nIndex);47+    friend class CReserveKey;48+public:49+    vector<unsigned char> GetKeyFromKeyPool();50 };51 52 bool LoadWallet(bool& fFirstRunRet);53@@ -406,3 +442,49 @@54     return CWalletDB().WriteName(strAddress, strName);55 }56 57+class CReserveKey58+{59+protected:60+    int64 nIndex;61+    vector<unsigned char> vchPubKey;62+public:63+    CReserveKey()64+    {65+        nIndex = -1;66+    }67+68+    ~CReserveKey()69+    {70+        if (!fShutdown)71+            ReturnKey();72+    }73+74+    vector<unsigned char> GetReservedKey()75+    {76+        if (nIndex == -1)77+        {78+            CKeyPool keypool;79+            CWalletDB().ReserveKeyFromKeyPool(nIndex, keypool);80+            vchPubKey = keypool.vchPubKey;81+        }82+        assert(!vchPubKey.empty());83+        return vchPubKey;84+    }85+86+    void KeepKey()87+    {88+        if (nIndex != -1)89+            CWalletDB().KeepKey(nIndex);90+        nIndex = -1;91+        vchPubKey.clear();92+    }93+94+    void ReturnKey()95+    {96+        if (nIndex != -1)97+            CWalletDB::ReturnKey(nIndex);98+        nIndex = -1;99+        vchPubKey.clear();100+    }101+};102+

headers.h (modified)

1--- v0.3.13/headers.h2+++ v0.3.14/headers.h3@@ -70,6 +70,7 @@4 #include <boost/filesystem/fstream.hpp>5 #include <boost/algorithm/string.hpp>6 #include <boost/thread.hpp>7+#include <boost/interprocess/sync/file_lock.hpp>8 #include <boost/interprocess/sync/interprocess_mutex.hpp>9 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>10 #include <boost/date_time/gregorian/gregorian_types.hpp>

init.cpp (modified)

1--- v0.3.13/init.cpp2+++ v0.3.14/init.cpp3@@ -165,17 +165,34 @@4             "  bitcoin [options] help              \t\t  " + _("List commands\n") +5             "  bitcoin [options] help <command>    \t\t  " + _("Get help for a command\n") +6           _("Options:\n") +7-            "  -conf=<file>    \t  " + _("Specify configuration file (default: bitcoin.conf)\n") +8-            "  -gen            \t  " + _("Generate coins\n") +9-            "  -gen=0          \t  " + _("Don't generate coins\n") +10-            "  -min            \t  " + _("Start minimized\n") +11-            "  -datadir=<dir>  \t  " + _("Specify data directory\n") +12-            "  -proxy=<ip:port>\t  " + _("Connect through socks4 proxy\n") +13-            "  -addnode=<ip>   \t  " + _("Add a node to connect to\n") +14-            "  -connect=<ip>   \t  " + _("Connect only to the specified node\n") +15-            "  -server         \t  " + _("Accept command line and JSON-RPC commands\n") +16-            "  -daemon         \t  " + _("Run in the background as a daemon and accept commands\n") +17-            "  -?              \t  " + _("This help message\n");18+            "  -conf=<file>     \t\t  " + _("Specify configuration file (default: bitcoin.conf)\n") +19+            "  -gen             \t\t  " + _("Generate coins\n") +20+            "  -gen=0           \t\t  " + _("Don't generate coins\n") +21+            "  -min             \t\t  " + _("Start minimized\n") +22+            "  -datadir=<dir>   \t\t  " + _("Specify data directory\n") +23+            "  -proxy=<ip:port> \t  "   + _("Connect through socks4 proxy\n") +24+            "  -addnode=<ip>    \t  "   + _("Add a node to connect to\n") +25+            "  -connect=<ip>    \t\t  " + _("Connect only to the specified node\n") +26+            "  -server          \t\t  " + _("Accept command line and JSON-RPC commands\n") +27+            "  -daemon          \t\t  " + _("Run in the background as a daemon and accept commands\n") +28+            "  -testnet         \t\t  " + _("Use the test network\n") +29+            "  -rpcuser=<user>  \t  "   + _("Username for JSON-RPC connections\n") +30+            "  -rpcpassword=<pw>\t  "   + _("Password for JSON-RPC connections\n") +31+            "  -rpcport=<port>  \t\t  " + _("Listen for JSON-RPC connections on <port>\n") +32+            "  -rpcallowip=<ip> \t\t  " + _("Allow JSON-RPC connections from specified IP address\n") +33+            "  -rpcconnect=<ip> \t  "   + _("Send commands to node running on <ip>\n");34+35+#ifdef USE_SSL36+        strUsage += string() +37+            _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)\n") +38+            "  -rpcssl=1                             \t  " + _("Use OpenSSL (https) for JSON-RPC connections\n") +39+            "  -rpcsslcertificatchainfile=<file.cert>\t  " + _("Server certificate file (default: server.cert)\n") +40+            "  -rpcsslprivatekeyfile=<file.pem>      \t  " + _("Server private key (default: server.pem)\n") +41+            "  -rpcsslciphers=<ciphers>              \t  " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)\n");42+#endif43+44+        strUsage += string() +45+            "  -?               \t\t  " + _("This help message\n");46 47 #if defined(__WXMSW__) && defined(GUI)48         // Tabs make the columns line up in the message box49@@ -193,6 +210,9 @@50 51     if (mapArgs.count("-printtodebugger"))52         fPrintToDebugger = true;53+54+    if (mapArgs.count("-testnet"))55+        fTestNet = true;56 57     if (fCommandLine)58     {59@@ -224,8 +244,7 @@60     // Required to protect the database files if we're going to keep deleting log.*61     //62 #if defined(__WXMSW__) && defined(GUI)63-    // todo: wxSingleInstanceChecker wasn't working on Linux, never deleted its lock file64-    //  maybe should go by whether successfully bind port 8333 instead65+    // wxSingleInstanceChecker doesn't work on Linux66     wxString strMutexName = wxString("bitcoin_running.") + getenv("HOMEPATH");67     for (int i = 0; i < strMutexName.size(); i++)68         if (!isalnum(strMutexName[i]))69@@ -237,7 +256,6 @@70         unsigned int nStart = GetTime();71         loop72         {73-            // TODO: find out how to do this in Linux, or replace with wxWidgets commands74             // Show the previous instance and exit75             HWND hwndPrev = FindWindowA("wxWindowClassNR", "Bitcoin");76             if (hwndPrev)77@@ -261,8 +279,18 @@78     }79 #endif80 81+    // Make sure only a single bitcoin process is using the data directory.82+    string strLockFile = GetDataDir() + "/.lock";83+    FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.84+    fclose(file);85+    static boost::interprocess::file_lock lock(strLockFile.c_str());86+    if (!lock.try_lock())87+    {88+        wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");89+        return false;90+    }91+92     // Bind to the port early so we can tell if another instance is already running.93-    // This is a backup to wxSingleInstanceChecker, which doesn't work on Linux.94     string strErrors;95     if (!BindListenPort(strErrors))96     {

irc.cpp (modified)

1--- v0.3.13/irc.cpp2+++ v0.3.14/irc.cpp3@@ -126,7 +126,7 @@4     }5 }6 7-int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL)8+int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)9 {10     loop11     {12@@ -141,6 +141,8 @@13             return 2;14         if (psz3 && strLine.find(psz3) != -1)15             return 3;16+        if (psz4 && strLine.find(psz4) != -1)17+            return 4;18     }19 }20 21@@ -210,7 +212,7 @@22                 return;23         }24 25-        if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname"))26+        if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))27         {28             closesocket(hSocket);29             hSocket = INVALID_SOCKET;30@@ -250,8 +252,8 @@31         }32         Sleep(500);33 34-        Send(hSocket, "JOIN #bitcoin\r");35-        Send(hSocket, "WHO #bitcoin\r");36+        Send(hSocket, fTestNet ? "JOIN #bitcoinTEST\r" : "JOIN #bitcoin\r");37+        Send(hSocket, fTestNet ? "WHO #bitcoinTEST\r"  : "WHO #bitcoin\r");38 39         int64 nStart = GetTime();40         string strLine;

main.cpp (modified)

1--- v0.3.13/main.cpp2+++ v0.3.14/main.cpp3@@ -21,7 +21,8 @@4 map<COutPoint, CInPoint> mapNextTx;5 6 map<uint256, CBlockIndex*> mapBlockIndex;7-const uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");8+uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");9+CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);10 CBlockIndex* pindexGenesisBlock = NULL;11 int nBestHeight = -1;12 CBigNum bnBestChainWork = 0;13@@ -143,7 +144,7 @@14         }15 16         //// debug print17-        printf("AddToWallet %s  %s%s\n", wtxIn.GetHash().ToString().substr(0,6).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));18+        printf("AddToWallet %s  %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));19 20         // Write to disk21         if (fInsertedNew || fUpdated)22@@ -158,7 +159,8 @@23             if (txout.scriptPubKey == scriptDefaultKey)24             {25                 CWalletDB walletdb;26-                walletdb.WriteDefaultKey(GenerateNewKey());27+                vchDefaultKey = walletdb.GetKeyFromKeyPool();28+                walletdb.WriteDefaultKey(vchDefaultKey);29                 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");30             }31         }32@@ -587,7 +589,7 @@33     {34         if (pfMissingInputs)35             *pfMissingInputs = true;36-        return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,6).c_str());37+        return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());38     }39 40     // Store transaction in memory41@@ -606,7 +608,7 @@42     if (ptxOld)43         EraseFromWallet(ptxOld->GetHash());44 45-    printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,6).c_str());46+    printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());47     return true;48 }49 50@@ -775,7 +777,7 @@51         uint256 hash = GetHash();52         if (!txdb.ContainsTx(hash))53         {54-            printf("Relaying wtx %s\n", hash.ToString().substr(0,6).c_str());55+            printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());56             RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);57         }58     }59@@ -985,7 +987,8 @@60             txindex.vSpent[prevout.n].SetNull();61 62             // Write back63-            txdb.UpdateTxIndex(prevout.hash, txindex);64+            if (!txdb.UpdateTxIndex(prevout.hash, txindex))65+                return error("DisconnectInputs() : UpdateTxIndex failed");66         }67     }68 69@@ -1022,7 +1025,7 @@70                 fFound = txdb.ReadTxIndex(prevout.hash, txindex);71             }72             if (!fFound && (fBlock || fMiner))73-                return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,6).c_str(),  prevout.hash.ToString().substr(0,6).c_str());74+                return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());75 76             // Read txPrev77             CTransaction txPrev;78@@ -1032,7 +1035,7 @@79                 CRITICAL_BLOCK(cs_mapTransactions)80                 {81                     if (!mapTransactions.count(prevout.hash))82-                        return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,6).c_str(),  prevout.hash.ToString().substr(0,6).c_str());83+                        return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());84                     txPrev = mapTransactions[prevout.hash];85                 }86                 if (!fFound)87@@ -1042,11 +1045,11 @@88             {89                 // Get prev tx from disk90                 if (!txPrev.ReadFromDisk(txindex.pos))91-                    return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,6).c_str(),  prevout.hash.ToString().substr(0,6).c_str());92+                    return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());93             }94 95             if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())96-                return error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,6).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,6).c_str(), txPrev.ToString().c_str());97+                return error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str());98 99             // If prev is coinbase, check that it's matured100             if (txPrev.IsCoinBase())101@@ -1056,11 +1059,11 @@102 103             // Verify signature104             if (!VerifySignature(txPrev, *this, i))105-                return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,6).c_str());106+                return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());107 108             // Check for conflicts109             if (!txindex.vSpent[prevout.n].IsNull())110-                return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,6).c_str(), txindex.vSpent[prevout.n].ToString().c_str());111+                return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());112 113             // Check for negative or overflow input values114             nValueIn += txPrev.vout[prevout.n].nValue;115@@ -1072,18 +1075,23 @@116 117             // Write back118             if (fBlock)119-                txdb.UpdateTxIndex(prevout.hash, txindex);120+            {121+                if (!txdb.UpdateTxIndex(prevout.hash, txindex))122+                    return error("ConnectInputs() : UpdateTxIndex failed");123+            }124             else if (fMiner)125+            {126                 mapTestPool[prevout.hash] = txindex;127+            }128         }129 130         if (nValueIn < GetValueOut())131-            return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,6).c_str());132+            return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());133 134         // Tally transaction fees135         int64 nTxFee = nValueIn - GetValueOut();136         if (nTxFee < 0)137-            return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,6).c_str());138+            return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());139         if (nTxFee < nMinFee)140             return false;141         nFees += nTxFee;142@@ -1168,7 +1176,8 @@143     {144         CDiskBlockIndex blockindexPrev(pindex->pprev);145         blockindexPrev.hashNext = 0;146-        txdb.WriteBlockIndex(blockindexPrev);147+        if (!txdb.WriteBlockIndex(blockindexPrev))148+            return error("DisconnectBlock() : WriteBlockIndex failed");149     }150 151     return true;152@@ -1203,7 +1212,8 @@153     {154         CDiskBlockIndex blockindexPrev(pindex->pprev);155         blockindexPrev.hashNext = pindex->GetBlockHash();156-        txdb.WriteBlockIndex(blockindexPrev);157+        if (!txdb.WriteBlockIndex(blockindexPrev))158+            return error("ConnectBlock() : WriteBlockIndex failed");159     }160 161     // Watch for transactions paying to me162@@ -1282,8 +1292,9 @@163     if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))164         return error("Reorganize() : WriteHashBestChain failed");165 166-    // Commit now because resurrecting could take some time167-    txdb.TxnCommit();168+    // Make sure it's successfully written to disk before changing memory structure169+    if (!txdb.TxnCommit())170+        return error("Reorganize() : TxnCommit failed");171 172     // Disconnect shorter branch173     foreach(CBlockIndex* pindex, vDisconnect)174@@ -1314,8 +1325,10 @@175     txdb.TxnBegin();176     if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)177     {178+        txdb.WriteHashBestChain(hash);179+        if (!txdb.TxnCommit())180+            return error("SetBestChain() : TxnCommit failed");181         pindexGenesisBlock = pindexNew;182-        txdb.WriteHashBestChain(hash);183     }184     else if (hashPrevBlock == hashBestChain)185     {186@@ -1326,7 +1339,10 @@187             InvalidChainFound(pindexNew);188             return error("SetBestChain() : ConnectBlock failed");189         }190-        txdb.TxnCommit();191+        if (!txdb.TxnCommit())192+            return error("SetBestChain() : TxnCommit failed");193+194+        // Add to current best branch195         pindexNew->pprev->pnext = pindexNew;196 197         // Delete redundant memory transactions198@@ -1343,7 +1359,6 @@199             return error("SetBestChain() : Reorganize failed");200         }201     }202-    txdb.TxnCommit();203 204     // New best block205     hashBestChain = hash;206@@ -1473,21 +1488,13 @@207             return error("AcceptBlock() : contains a non-final transaction");208 209     // Check that the block chain matches the known block chain up to a checkpoint210-    if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||211-        (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||212-        (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||213-        (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||214-        (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")))215-        return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);216-217-    // Scanback checkpoint lockin218-    for (CBlockIndex* pindex = pindexPrev; pindex->nHeight >= 74000; pindex = pindex->pprev)219-    {220-        if (pindex->nHeight == 74000 && pindex->GetBlockHash() != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20"))221-            return error("AcceptBlock() : rejected by scanback lockin at %d", pindex->nHeight);222-        if (pindex->nHeight == 74638 && pindex->GetBlockHash() == uint256("0x0000000000790ab3f22ec756ad43b6ab569abf0bddeb97c67a6f7b1470a7ec1c"))223-            return error("AcceptBlock() : rejected by scanback lockin at %d", pindex->nHeight);224-    }225+    if (!fTestNet)226+        if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||227+            (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||228+            (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||229+            (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||230+            (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")))231+            return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);232 233     // Write block to history file234     if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))235@@ -1678,6 +1685,16 @@236 237 bool LoadBlockIndex(bool fAllowNew)238 {239+    if (fTestNet)240+    {241+        hashGenesisBlock = uint256("0x0000000224b1593e3ff16a0e3b61285bbc393a39f78c8aa48c456142671f7110");242+        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);243+        pchMessageStart[0] = 0xfa;244+        pchMessageStart[1] = 0xbf;245+        pchMessageStart[2] = 0xb5;246+        pchMessageStart[3] = 0xda;247+    }248+249     //250     // Load block index251     //252@@ -1718,13 +1735,19 @@253         block.nBits    = 0x1d00ffff;254         block.nNonce   = 2083236893;255 256-            //// debug print257-            printf("%s\n", block.GetHash().ToString().c_str());258-            printf("%s\n", hashGenesisBlock.ToString().c_str());259-            printf("%s\n", block.hashMerkleRoot.ToString().c_str());260-            assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));261-            block.print();262-263+        if (fTestNet)264+        {265+            block.nTime    = 1279232055;266+            block.nBits    = 0x1d07fff8;267+            block.nNonce   = 81622180;268+        }269+270+        //// debug print271+        printf("%s\n", block.GetHash().ToString().c_str());272+        printf("%s\n", hashGenesisBlock.ToString().c_str());273+        printf("%s\n", block.hashMerkleRoot.ToString().c_str());274+        assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));275+        block.print();276         assert(block.GetHash() == hashGenesisBlock);277 278         // Start new block file279@@ -1948,7 +1971,7 @@280 {281     switch (inv.type)282     {283-    case MSG_TX:    return mapTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);284+    case MSG_TX:    return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);285     case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);286     }287     // Don't know what it is, just say we already got one288@@ -1958,7 +1981,10 @@289 290 291 292-293+// The message start string is designed to be unlikely to occur in normal data.294+// The characters are rarely used upper ascii, not valid as UTF-8, and produce295+// a large 4-byte int at any alignment.296+char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };297 298 299 bool ProcessMessages(CNode* pfrom)300@@ -2017,28 +2043,27 @@301         if (nMessageSize > vRecv.size())302         {303             // Rewind and wait for rest of message304-            ///// need a mechanism to give up waiting for overlong message size error305             vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());306             break;307+        }308+309+        // Checksum310+        if (vRecv.GetVersion() >= 209)311+        {312+            uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);313+            unsigned int nChecksum = 0;314+            memcpy(&nChecksum, &hash, sizeof(nChecksum));315+            if (nChecksum != hdr.nChecksum)316+            {317+                printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",318+                       strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);319+                continue;320+            }321         }322 323         // Copy message to its own buffer324         CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);325         vRecv.ignore(nMessageSize);326-327-        // Checksum328-        if (vRecv.GetVersion() >= 209)329-        {330-            uint256 hash = Hash(vMsg.begin(), vMsg.end());331-            unsigned int nChecksum = 0;332-            memcpy(&nChecksum, &hash, sizeof(nChecksum));333-            if (nChecksum != hdr.nChecksum)334-            {335-                printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",336-                       strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);337-                continue;338-            }339-        }340 341         // Process message342         bool fRet = false;343@@ -2126,6 +2151,7 @@344         // Disconnect if we connected to ourself345         if (nNonce == nLocalHostNonce && nNonce > 1)346         {347+            printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());348             pfrom->fDisconnect = true;349             return true;350         }351@@ -2202,20 +2228,27 @@352                 addr.nTime -= 5 * 24 * 60 * 60;353             AddAddress(addr);354             pfrom->AddAddressKnown(addr);355-            if (!pfrom->fGetAddr && addr.IsRoutable())356+            if (!pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())357             {358                 // Relay to a limited number of other nodes359                 CRITICAL_BLOCK(cs_vNodes)360                 {361-                    // Use deterministic randomness to send to362-                    // the same places for 12 hours at a time363+                    // Use deterministic randomness to send to the same nodes for 24 hours364+                    // at a time so the setAddrKnowns of the chosen nodes prevent repeats365                     static uint256 hashSalt;366                     if (hashSalt == 0)367                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));368-                    uint256 hashRand = addr.ip ^ ((GetTime()+addr.ip)/(12*60*60)) ^ hashSalt;369+                    uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));370+                    hashRand = Hash(BEGIN(hashRand), END(hashRand));371                     multimap<uint256, CNode*> mapMix;372                     foreach(CNode* pnode, vNodes)373-                        mapMix.insert(make_pair(hashRand = Hash(BEGIN(hashRand), END(hashRand)), pnode));374+                    {375+                        unsigned int nPointer;376+                        memcpy(&nPointer, &pnode, sizeof(nPointer));377+                        uint256 hashKey = hashRand ^ nPointer;378+                        hashKey = Hash(BEGIN(hashKey), END(hashKey));379+                        mapMix.insert(make_pair(hashKey, pnode));380+                    }381                     int nRelayNodes = 2;382                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)383                         ((*mi).second)->PushAddress(addr);384@@ -2386,7 +2419,7 @@385 386                     if (tx.AcceptToMemoryPool(true))387                     {388-                        printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());389+                        printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());390                         AddToWalletIfMine(tx, NULL);391                         RelayMessage(inv, vMsg);392                         mapAlreadyAskedFor.erase(inv);393@@ -2400,7 +2433,7 @@394         }395         else if (fMissingInputs)396         {397-            printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());398+            printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());399             AddOrphanTx(vMsg);400         }401     }402@@ -2427,15 +2460,20 @@403     {404         // Nodes rebroadcast an addr every 24 hours405         pfrom->vAddrToSend.clear();406-        int64 nSince = GetAdjustedTime() - 6 * 60 * 60; // in the last 6 hours407+        int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours408         CRITICAL_BLOCK(cs_mapAddresses)409         {410+            unsigned int nCount = 0;411             foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)412             {413-                if (fShutdown)414-                    return true;415                 const CAddress& addr = item.second;416                 if (addr.nTime > nSince)417+                    nCount++;418+            }419+            foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)420+            {421+                const CAddress& addr = item.second;422+                if (addr.nTime > nSince && GetRand(nCount) < 2500)423                     pfrom->PushAddress(addr);424             }425         }426@@ -2458,7 +2496,7 @@427 428         // Keep giving the same key to the same ip until they use it429         if (!mapReuseKey.count(pfrom->addr.ip))430-            mapReuseKey[pfrom->addr.ip] = GenerateNewKey();431+            mapReuseKey[pfrom->addr.ip] = CWalletDB().GetKeyFromKeyPool();432 433         // Send back approval of order and pubkey to use434         CScript scriptPubKey;435@@ -2774,7 +2812,7 @@436         vnThreadsRunning[3]--;437         PrintException(NULL, "ThreadBitcoinMiner()");438     }439-    UIThreadCall(bind(CalledSetStatusBar, "", 0));440+    UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));441     nHPSTimerStart = 0;442     if (vnThreadsRunning[3] == 0)443         dHashesPerSec = 0;444@@ -2831,6 +2869,10 @@445     bool fUseSSE2 = ((fIntel && nFamily * 10000 + nModel >=  60026) ||446                      (fAMD   && nFamily * 10000 + nModel >= 160010));447 448+    // AMD reports a lower model number in 64-bit mode449+    if (fAMD && sizeof(void*) > 4 && nFamily * 10000 + nModel >= 160000)450+        fUseSSE2 = true;451+452     static bool fPrinted;453     if (!fPrinted)454     {455@@ -2915,12 +2957,13 @@456     if (mapArgs.count("-4way"))457         f4WaySSE2 = (mapArgs["-4way"] != "0");458 459-    CKey key;460-    key.MakeNewKey();461-    CBigNum bnExtraNonce = 0;462+    CReserveKey reservekey;463+    unsigned int nExtraNonce = 0;464+    int64 nPrevTime = 0;465     while (fGenerateBitcoins)466     {467-        Sleep(50);468+        if (AffinityBugWorkaround(ThreadBitcoinMiner))469+            return;470         if (fShutdown)471             return;472         while (vNodes.empty() || IsInitialBlockDownload())473@@ -2943,9 +2986,15 @@474         CTransaction txNew;475         txNew.vin.resize(1);476         txNew.vin[0].prevout.SetNull();477-        txNew.vin[0].scriptSig << nBits << ++bnExtraNonce;478+        int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());479+        if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)480+        {481+            nExtraNonce = 1;482+            nPrevTime = nNow;483+        }484+        txNew.vin[0].scriptSig << nBits << CBigNum(nExtraNonce);485         txNew.vout.resize(1);486-        txNew.vout[0].scriptPubKey << key.GetPubKey() << OP_CHECKSIG;487+        txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;488 489 490         //491@@ -3031,9 +3080,9 @@492         tmpworkspace& tmp = *(tmpworkspace*)alignup<16>(tmpbuf);493 494         tmp.block.nVersion       = pblock->nVersion;495-        tmp.block.hashPrevBlock  = pblock->hashPrevBlock  = (pindexPrev ? pindexPrev->GetBlockHash() : 0);496+        tmp.block.hashPrevBlock  = pblock->hashPrevBlock  = pindexPrev->GetBlockHash();497         tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();498-        tmp.block.nTime          = pblock->nTime          = max((pindexPrev ? pindexPrev->GetMedianTimePast()+1 : 0), GetAdjustedTime());499+        tmp.block.nTime          = pblock->nTime          = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());500         tmp.block.nBits          = pblock->nBits          = nBits;501         tmp.block.nNonce         = pblock->nNonce         = 0;502 503@@ -3095,10 +3144,8 @@504                     {505                         if (pindexPrev == pindexBest)506                         {507-                            // Save key508-                            if (!AddKey(key))509-                                return;510-                            key.MakeNewKey();511+                            // Remove key from key pool512+                            reservekey.KeepKey();513 514                             // Track how many getdata requests this block gets515                             CRITICAL_BLOCK(cs_mapRequestCount)516@@ -3136,7 +3183,7 @@517                         nHPSTimerStart = GetTimeMillis();518                         nHashCounter = 0;519                         string strStatus = strprintf("    %.0f khash/s", dHashesPerSec/1000.0);520-                        UIThreadCall(bind(CalledSetStatusBar, strStatus, 0));521+                        UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));522                         static int64 nLogTime;523                         if (GetTime() - nLogTime > 30 * 60)524                         {525@@ -3204,9 +3251,7 @@526         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)527         {528             CWalletTx* pcoin = &(*it).second;529-            if (!pcoin->IsFinal() || pcoin->fSpent)530-                continue;531-            if (pcoin->GetDepthInMainChain() < 1 && pcoin->GetDebit() <= 0)532+            if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())533                 continue;534             nTotal += pcoin->GetCredit(true);535         }536@@ -3237,9 +3282,7 @@537 538        foreach(CWalletTx* pcoin, vCoins)539        {540-            if (!pcoin->IsFinal() || pcoin->fSpent)541-                continue;542-            if (pcoin->GetDepthInMainChain() < 1 && pcoin->GetDebit() <= 0)543+            if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())544                 continue;545             int64 n = pcoin->GetCredit();546             if (n <= 0)547@@ -3328,7 +3371,7 @@548 549 550 551-bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet)552+bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRequiredRet)553 {554     nFeeRequiredRet = 0;555     CRITICAL_BLOCK(cs_main)556@@ -3372,18 +3415,20 @@557                     //  rediscover unknown transactions that were written with keys of ours to recover558                     //  post-backup change.559 560-                    // New private key561-                    if (keyRet.IsNull())562-                        keyRet.MakeNewKey();563+                    // Reserve a new key pair from key pool564+                    vector<unsigned char> vchPubKey = reservekey.GetReservedKey();565+                    assert(mapKeys.count(vchPubKey));566 567                     // Fill a vout to ourself, using same address type as the payment568                     CScript scriptChange;569                     if (scriptPubKey.GetBitcoinAddressHash160() != 0)570-                        scriptChange.SetBitcoinAddress(keyRet.GetPubKey());571+                        scriptChange.SetBitcoinAddress(vchPubKey);572                     else573-                        scriptChange << keyRet.GetPubKey() << OP_CHECKSIG;574+                        scriptChange << vchPubKey << OP_CHECKSIG;575                     wtxNew.vout.push_back(CTxOut(nChange, scriptChange));576                 }577+                else578+                    reservekey.ReturnKey();579 580                 // Fill a vout to the payee581                 if (fChangeFirst)582@@ -3426,7 +3471,7 @@583 }584 585 // Call after CreateTransaction unless you want to abort586-bool CommitTransaction(CWalletTx& wtxNew, const CKey& key)587+bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)588 {589     CRITICAL_BLOCK(cs_main)590     {591@@ -3438,9 +3483,8 @@592             // maybe makes sense; please don't do it anywhere else.593             CWalletDB walletdb("r");594 595-            // Add the change's private key to wallet596-            if (!key.IsNull() && !AddKey(key))597-                throw runtime_error("CommitTransaction() : AddKey failed");598+            // Take key pair from key pool so it won't be used again599+            reservekey.KeepKey();600 601             // Add tx to wallet, because if it has change it's also ours,602             // otherwise just for transaction history.603@@ -3482,9 +3526,9 @@604 {605     CRITICAL_BLOCK(cs_main)606     {607-        CKey key;608+        CReserveKey reservekey;609         int64 nFeeRequired;610-        if (!CreateTransaction(scriptPubKey, nValue, wtxNew, key, nFeeRequired))611+        if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))612         {613             string strError;614             if (nValue + nFeeRequired > GetBalance())615@@ -3498,7 +3542,7 @@616         if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))617             return "ABORTED";618 619-        if (!CommitTransaction(wtxNew, key))620+        if (!CommitTransaction(wtxNew, reservekey))621             return _("Error: The transaction was rejected.  This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");622     }623     MainFrameRepaint();

main.h (modified)

1--- v0.3.13/main.h2+++ v0.3.14/main.h3@@ -22,7 +22,6 @@4 static const int64 MAX_MONEY = 21000000 * COIN;5 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }6 static const int COINBASE_MATURITY = 100;7-static const CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);8 9 10 11@@ -31,7 +30,8 @@12 13 extern CCriticalSection cs_main;14 extern map<uint256, CBlockIndex*> mapBlockIndex;15-extern const uint256 hashGenesisBlock;16+extern uint256 hashGenesisBlock;17+extern CBigNum bnProofOfWorkLimit;18 extern CBlockIndex* pindexGenesisBlock;19 extern int nBestHeight;20 extern CBigNum bnBestChainWork;21@@ -76,8 +76,8 @@22 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);23 bool SendMessages(CNode* pto, bool fSendTrickle);24 int64 GetBalance();25-bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet);26-bool CommitTransaction(CWalletTx& wtxNew, const CKey& key);27+bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRequiredRet);28+bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);29 bool BroadcastTransaction(CWalletTx& wtxNew);30 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);31 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);32@@ -195,7 +195,7 @@33 34     string ToString() const35     {36-        return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);37+        return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);38     }39 40     void print() const41@@ -361,7 +361,7 @@42     {43         if (scriptPubKey.size() < 6)44             return "CTxOut(error)";45-        return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());46+        return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());47     }48 49     void print() const50@@ -599,7 +599,7 @@51     {52         string str;53         str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",54-            GetHash().ToString().substr(0,6).c_str(),55+            GetHash().ToString().substr(0,10).c_str(),56             nVersion,57             vin.size(),58             vout.size(),59@@ -785,6 +785,37 @@60         nCreditCached = CTransaction::GetCredit();61         fCreditCached = true;62         return nCreditCached;63+    }64+65+    bool IsConfirmed() const66+    {67+        map<uint256, const CMerkleTx*> mapPrev;68+        vector<const CMerkleTx*> vWorkQueue;69+        vWorkQueue.reserve(vtxPrev.size()+1);70+        vWorkQueue.push_back(this);71+        for (int i = 0; i < vWorkQueue.size(); i++)72+        {73+            const CMerkleTx* ptx = vWorkQueue[i];74+75+            if (!ptx->IsFinal())76+                return false;77+            if (ptx->GetDepthInMainChain() >= 1)78+                return true;79+            if (ptx->GetDebit() <= 0)80+                return false;81+82+            if (mapPrev.empty())83+                foreach(const CMerkleTx& tx, vtxPrev)84+                    mapPrev[tx.GetHash()] = &tx;85+86+            foreach(const CTxIn& txin, ptx->vin)87+            {88+                if (!mapPrev.count(txin.prevout.hash))89+                    return false;90+                vWorkQueue.push_back(mapPrev[txin.prevout.hash]);91+            }92+        }93+        return true;94     }95 96     bool WriteToDisk()97@@ -1065,7 +1096,7 @@98             GetHash().ToString().substr(0,20).c_str(),99             nVersion,100             hashPrevBlock.ToString().substr(0,20).c_str(),101-            hashMerkleRoot.ToString().substr(0,6).c_str(),102+            hashMerkleRoot.ToString().substr(0,10).c_str(),103             nTime, nBits, nNonce,104             vtx.size());105         for (int i = 0; i < vtx.size(); i++)106@@ -1075,7 +1106,7 @@107         }108         printf("  vMerkleTree: ");109         for (int i = 0; i < vMerkleTree.size(); i++)110-            printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());111+            printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());112         printf("\n");113     }114 115@@ -1233,7 +1264,7 @@116     {117         return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",118             pprev, pnext, nFile, nBlockPos, nHeight,119-            hashMerkleRoot.ToString().substr(0,6).c_str(),120+            hashMerkleRoot.ToString().substr(0,10).c_str(),121             GetBlockHash().ToString().substr(0,20).c_str());122     }123 

makefile.osx (modified)

1--- v0.3.13/makefile.osx2+++ v0.3.14/makefile.osx3@@ -22,9 +22,10 @@4  $(DEPSDIR)/lib/libboost_filesystem.a \5  $(DEPSDIR)/lib/libboost_program_options.a \6  $(DEPSDIR)/lib/libboost_thread.a \7+ $(DEPSDIR)/lib/libssl.a \8  $(DEPSDIR)/lib/libcrypto.a 9 10-DEFS=$(shell $(DEPSDIR)/bin/wx-config --cxxflags) -D__WXMAC_OSX__ -DNOPCH -DMSG_NOSIGNAL=011+DEFS=$(shell $(DEPSDIR)/bin/wx-config --cxxflags) -D__WXMAC_OSX__ -DNOPCH -DMSG_NOSIGNAL=0 -DUSE_SSL12 13 DEBUGFLAGS=-g -DwxDEBUG_LEVEL=014 # ppc doesn't work because we don't support big-endian

makefile.unix (modified)

1--- v0.3.13/makefile.unix2+++ v0.3.14/makefile.unix3@@ -23,11 +23,14 @@4    -l boost_program_options \5    -l boost_thread \6    -l db_cxx \7+   -l ssl \8    -l crypto \9  -Wl,-Bdynamic \10-   -l gthread-2.011+   -l gthread-2.0 \12+   -l z \13+   -l dl14 15-DEFS=-D__WXGTK__ -DNOPCH -DFOURWAYSSE216+DEFS=-D__WXGTK__ -DNOPCH -DFOURWAYSSE2 -DUSE_SSL17 DEBUGFLAGS=-g -D__WXDEBUG__18 CFLAGS=-O2 -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(DEFS) $(INCLUDEPATHS)19 HEADERS=headers.h strlcpy.h serialize.h uint256.h util.h key.h bignum.h base58.h \

net.cpp (modified)

1--- v0.3.13/net.cpp2+++ v0.3.14/net.cpp3@@ -20,7 +20,7 @@4 //5 bool fClient = false;6 uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);7-CAddress addrLocalHost(0, DEFAULT_PORT, nLocalServices);8+CAddress addrLocalHost(0, 0, nLocalServices);9 CNode* pnodeLocalHost = NULL;10 uint64 nLocalHostNonce = 0;11 array<int, 10> vnThreadsRunning;12@@ -937,7 +937,7 @@13             // Add seed nodes if IRC isn't working14             static bool fSeedUsed;15             bool fTOR = (fUseProxy && addrProxy.port == htons(9050));16-            if (mapAddresses.empty() && (GetTime() - nStart > 60 || fTOR))17+            if (mapAddresses.empty() && (GetTime() - nStart > 60 || fTOR) && !fTestNet)18             {19                 for (int i = 0; i < ARRAYLEN(pnSeed); i++)20                 {21@@ -1006,7 +1006,7 @@22 23                 // Randomize the order in a deterministic way, putting the standard port first24                 int64 nRandomizer = (uint64)(nStart * 4951 + addr.nLastTry * 9567851 + addr.ip * 7789) % (2 * 60 * 60);25-                if (addr.port != DEFAULT_PORT)26+                if (addr.port != GetDefaultPort())27                     nRandomizer += 2 * 60 * 60;28 29                 // Last seen  Base retry frequency30@@ -1185,6 +1185,7 @@31 {32     strError = "";33     int nOne = 1;34+    addrLocalHost.port = GetDefaultPort();35 36 #ifdef __WXMSW__37     // Initialize Windows Sockets38@@ -1236,12 +1237,12 @@39     memset(&sockaddr, 0, sizeof(sockaddr));40     sockaddr.sin_family = AF_INET;41     sockaddr.sin_addr.s_addr = INADDR_ANY; // bind to all IPs on this computer42-    sockaddr.sin_port = DEFAULT_PORT;43+    sockaddr.sin_port = GetDefaultPort();44     if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)45     {46         int nErr = WSAGetLastError();47         if (nErr == WSAEADDRINUSE)48-            strError = strprintf("Unable to bind to port %d on this computer.  Bitcoin is probably already running.", ntohs(sockaddr.sin_port));49+            strError = strprintf(_("Unable to bind to port %d on this computer.  Bitcoin is probably already running."), ntohs(sockaddr.sin_port));50         else51             strError = strprintf("Error: Unable to bind to port %d on this computer (bind returned error %d)", ntohs(sockaddr.sin_port), nErr);52         printf("%s\n", strError.c_str());53@@ -1278,7 +1279,7 @@54                 printf("host ip %d: %s\n", i, CAddress(*(unsigned int*)phostent->h_addr_list[i]).ToStringIP().c_str());55             for (int i = 0; phostent->h_addr_list[i] != NULL; i++)56             {57-                CAddress addr(*(unsigned int*)phostent->h_addr_list[i], DEFAULT_PORT, nLocalServices);58+                CAddress addr(*(unsigned int*)phostent->h_addr_list[i], GetDefaultPort(), nLocalServices);59                 if (addr.IsValid() && addr.GetByte(3) != 127)60                 {61                     addrLocalHost = addr;62@@ -1306,7 +1307,7 @@63                     printf("ipv4 %s: %s\n", ifa->ifa_name, pszIP);64 65                 // Take the first IP that isn't loopback 127.x.x.x66-                CAddress addr(*(unsigned int*)&s4->sin_addr, DEFAULT_PORT, nLocalServices);67+                CAddress addr(*(unsigned int*)&s4->sin_addr, GetDefaultPort(), nLocalServices);68                 if (addr.IsValid() && addr.GetByte(3) != 127)69                 {70                     addrLocalHost = addr;

net.h (modified)

1--- v0.3.13/net.h2+++ v0.3.14/net.h3@@ -12,7 +12,7 @@4 5 6 7-static const unsigned short DEFAULT_PORT = 0x8d20; // htons(8333)8+inline unsigned short GetDefaultPort() { return fTestNet ? htons(18333) : htons(8333); }9 static const unsigned int PUBLISH_HOPS = 5;10 enum11 {12@@ -48,10 +48,7 @@13 //  (4) size14 //  (4) checksum15 16-// The message start string is designed to be unlikely to occur in normal data.17-// The characters are rarely used upper ascii, not valid as UTF-8, and produce18-// a large 4-byte int at any alignment.19-static const char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };20+extern char pchMessageStart[4];21 22 class CMessageHeader23 {24@@ -153,11 +150,11 @@25         Init();26     }27 28-    CAddress(unsigned int ipIn, unsigned short portIn=DEFAULT_PORT, uint64 nServicesIn=NODE_NETWORK)29+    CAddress(unsigned int ipIn, unsigned short portIn=0, uint64 nServicesIn=NODE_NETWORK)30     {31         Init();32         ip = ipIn;33-        port = portIn;34+        port = (portIn == 0 ? GetDefaultPort() : portIn);35         nServices = nServicesIn;36     }37 38@@ -188,7 +185,7 @@39         nServices = NODE_NETWORK;40         memcpy(pchReserved, pchIPv4, sizeof(pchReserved));41         ip = INADDR_NONE;42-        port = DEFAULT_PORT;43+        port = GetDefaultPort();44         nTime = GetAdjustedTime();45         nLastTry = 0;46     }47@@ -196,7 +193,7 @@48     bool SetAddress(const char* pszIn)49     {50         ip = INADDR_NONE;51-        port = DEFAULT_PORT;52+        port = GetDefaultPort();53         char psz[100];54         strlcpy(psz, pszIn, sizeof(psz));55         unsigned int a=0, b=0, c=0, d=0, e=0;

rpc.cpp (modified)

1--- v0.3.13/rpc.cpp2+++ v0.3.14/rpc.cpp3@@ -5,6 +5,12 @@4 #include "headers.h"5 #undef printf6 #include <boost/asio.hpp>7+#include <boost/iostreams/concepts.hpp>8+#include <boost/iostreams/stream.hpp>9+#ifdef USE_SSL10+#include <boost/asio/ssl.hpp> 11+typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> SSLStream;12+#endif13 #include "json/json_spirit_reader_template.h"14 #include "json/json_spirit_writer_template.h"15 #include "json/json_spirit_utils.h"16@@ -14,7 +20,7 @@17 // a certain size around 145MB.  If we need access to json_spirit outside this18 // file, we could use the compiled json_spirit option.19 20-using boost::asio::ip::tcp;21+using namespace boost::asio;22 using namespace json_spirit;23 24 void ThreadRPCServer2(void* parg);25@@ -275,7 +281,7 @@26         strLabel = params[0].get_str();27 28     // Generate a new key that is added to wallet29-    string strAddress = PubKeyToAddress(GenerateNewKey());30+    string strAddress = PubKeyToAddress(CWalletDB().GetKeyFromKeyPool());31 32     SetAddressBookName(strAddress, strLabel);33     return strAddress;34@@ -648,7 +654,28 @@35     return Value::null;36 }37 38-39+Value validateaddress(const Array& params, bool fHelp)40+{41+    if (fHelp || params.size() != 1)42+        throw runtime_error(43+            "validateaddress <bitcoinaddress>\n"44+            "Return information about <bitcoinaddress>.");45+46+    string strAddress = params[0].get_str();47+    uint160 hash160;48+    bool isValid = AddressToHash160(strAddress, hash160);49+50+    Object ret;51+    ret.push_back(Pair("isvalid", isValid));52+    if (isValid)53+    {54+        // Call Hash160ToAddress() so we always return current ADDRESSVERSION55+        // version of the address:56+        ret.push_back(Pair("address", Hash160ToAddress(hash160)));57+        ret.push_back(Pair("ismine", (mapPubKeys.count(hash160) > 0)));58+    }59+    return ret;60+}61 62 63 64@@ -689,6 +716,7 @@65     make_pair("listreceivedbyaddress", &listreceivedbyaddress),66     make_pair("listreceivedbylabel",   &listreceivedbylabel),67     make_pair("backupwallet",          &backupwallet),68+    make_pair("validateaddress",       &validateaddress),69 };70 map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));71 72@@ -709,6 +737,7 @@73     "getlabel",74     "getaddressesbylabel",75     "backupwallet",76+    "validateaddress",77 };78 set<string> setAllowInSafeMode(pAllowInSafeMode, pAllowInSafeMode + sizeof(pAllowInSafeMode)/sizeof(pAllowInSafeMode[0]));79 80@@ -777,7 +806,7 @@81         strMsg.c_str());82 }83 84-int ReadHTTPStatus(tcp::iostream& stream)85+int ReadHTTPStatus(std::basic_istream<char>& stream)86 {87     string str;88     getline(stream, str);89@@ -788,7 +817,7 @@90     return atoi(vWords[1].c_str());91 }92 93-int ReadHTTPHeader(tcp::iostream& stream, map<string, string>& mapHeadersRet)94+int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)95 {96     int nLen = 0;97     loop98@@ -812,7 +841,7 @@99     return nLen;100 }101 102-int ReadHTTP(tcp::iostream& stream, map<string, string>& mapHeadersRet, string& strMessageRet)103+int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)104 {105     mapHeadersRet.clear();106     strMessageRet = "";107@@ -930,8 +959,59 @@108     return false;109 }110 111-112-113+#ifdef USE_SSL114+//115+// IOStream device that speaks SSL but can also speak non-SSL116+//117+class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {118+public:119+    SSLIOStreamDevice(SSLStream &streamIn, bool fUseSSLIn) : stream(streamIn)120+    {121+        fUseSSL = fUseSSLIn;122+        fNeedHandshake = fUseSSLIn;123+    }124+125+    void handshake(ssl::stream_base::handshake_type role)126+    {127+        if (!fNeedHandshake) return;128+        fNeedHandshake = false;129+        stream.handshake(role);130+    }131+    std::streamsize read(char* s, std::streamsize n)132+    {133+        handshake(ssl::stream_base::server); // HTTPS servers read first134+        if (fUseSSL) return stream.read_some(asio::buffer(s, n));135+        return stream.next_layer().read_some(asio::buffer(s, n));136+    }137+    std::streamsize write(const char* s, std::streamsize n)138+    {139+        handshake(ssl::stream_base::client); // HTTPS clients write first140+        if (fUseSSL) return asio::write(stream, asio::buffer(s, n));141+        return asio::write(stream.next_layer(), asio::buffer(s, n));142+    }143+    bool connect(const std::string& server, const std::string& port)144+    {145+        ip::tcp::resolver resolver(stream.get_io_service());146+        ip::tcp::resolver::query query(server.c_str(), port.c_str());147+        ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);148+        ip::tcp::resolver::iterator end;149+        boost::system::error_code error = asio::error::host_not_found;150+        while (error && endpoint_iterator != end)151+        {152+            stream.lowest_layer().close();153+            stream.lowest_layer().connect(*endpoint_iterator++, error);154+        }155+        if (error)156+            return false;157+        return true;158+    }159+160+private:161+    bool fNeedHandshake;162+    bool fUseSSL;163+    SSLStream& stream;164+};165+#endif166 167 void ThreadRPCServer(void* parg)168 {169@@ -972,18 +1052,54 @@170         return;171     }172 173-    // Bind to loopback 127.0.0.1 so the socket can only be accessed locally174-    boost::asio::io_service io_service;175-    tcp::endpoint endpoint(mapArgs.count("-rpcallowip") ? asio::ip::address_v4::any() : asio::ip::address_v4::loopback(), 8332);176-    tcp::acceptor acceptor(io_service, endpoint);177+    bool fUseSSL = (mapArgs.count("-rpcssl") > 0);178+    asio::ip::address bindAddress = mapArgs.count("-rpcallowip") ? asio::ip::address_v4::any() : asio::ip::address_v4::loopback();179+180+    asio::io_service io_service;181+    ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 8332));182+    ip::tcp::acceptor acceptor(io_service, endpoint);183+184+#ifdef USE_SSL185+    ssl::context context(io_service, ssl::context::sslv23);186+    if (fUseSSL)187+    {188+        context.set_options(ssl::context::no_sslv2);189+        filesystem::path certfile = GetArg("-rpcsslcertificatechainfile", "server.cert");190+        if (!certfile.is_complete()) certfile = filesystem::path(GetDataDir()) / certfile;191+        if (filesystem::exists(certfile)) context.use_certificate_chain_file(certfile.string().c_str());192+        else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", certfile.string().c_str());193+        filesystem::path pkfile = GetArg("-rpcsslprivatekeyfile", "server.pem");194+        if (!pkfile.is_complete()) pkfile = filesystem::path(GetDataDir()) / pkfile;195+        if (filesystem::exists(pkfile)) context.use_private_key_file(pkfile.string().c_str(), ssl::context::pem);196+        else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pkfile.string().c_str());197+198+        string ciphers = GetArg("-rpcsslciphers",199+                                         "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");200+        SSL_CTX_set_cipher_list(context.impl(), ciphers.c_str());201+    }202+#else203+    if (fUseSSL)204+        throw runtime_error("-rpcssl=true, but bitcoin compiled without full openssl libraries.");205+#endif206 207     loop208     {209         // Accept connection210-        tcp::iostream stream;211-        tcp::endpoint peer;212+#ifdef USE_SSL213+        SSLStream sslStream(io_service, context);214+        SSLIOStreamDevice d(sslStream, fUseSSL);215+        iostreams::stream<SSLIOStreamDevice> stream(d);216+#else217+        ip::tcp::iostream stream;218+#endif219+220+        ip::tcp::endpoint peer;221         vnThreadsRunning[4]--;222+#ifdef USE_SSL223+        acceptor.accept(sslStream.lowest_layer(), peer);224+#else225         acceptor.accept(*stream.rdbuf(), peer);226+#endif227         vnThreadsRunning[4]++;228         if (fShutdown)229             return;230@@ -1102,9 +1218,25 @@231                 GetConfigFile().c_str()));232 233     // Connect to localhost234-    tcp::iostream stream(GetArg("-rpcconnect", "127.0.0.1"), "8332");235+    bool fUseSSL = (mapArgs.count("-rpcssl") > 0);236+#ifdef USE_SSL237+    asio::io_service io_service;238+    ssl::context context(io_service, ssl::context::sslv23);239+    context.set_options(ssl::context::no_sslv2);240+    SSLStream sslStream(io_service, context);241+    SSLIOStreamDevice d(sslStream, fUseSSL);242+    iostreams::stream<SSLIOStreamDevice> stream(d);243+    if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332")))244+        throw runtime_error("couldn't connect to server");245+#else246+    if (fUseSSL)247+        throw runtime_error("-rpcssl=true, but bitcoin compiled without full openssl libraries.");248+249+    ip::tcp::iostream stream(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332"));250     if (stream.fail())251         throw runtime_error("couldn't connect to server");252+#endif253+254 255     // HTTP basic authentication256     string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);

script.cpp (modified)

1--- v0.3.13/script.cpp2+++ v0.3.14/script.cpp3@@ -776,16 +776,11 @@4                         return false;5 6                     int nKeysCount = CastToBigNum(stacktop(-i)).getint();7-                    if (nKeysCount < 0)8-                        return false;9-                    if (nBestHeight > 84000)10-                    {11-                        if (nKeysCount > 20)12-                            return false;13-                        nOpCount += nKeysCount;14-                        if (nOpCount > 201)15-                            return false;16-                    }17+                    if (nKeysCount < 0 || nKeysCount > 20)18+                        return false;19+                    nOpCount += nKeysCount;20+                    if (nOpCount > 201)21+                        return false;22                     int ikey = ++i;23                     i += nKeysCount;24                     if (stack.size() < i)

serialize.h (modified)

1--- v0.3.13/serialize.h2+++ v0.3.14/serialize.h3@@ -22,7 +22,7 @@4 class CAutoFile;5 static const unsigned int MAX_SIZE = 0x02000000;6 7-static const int VERSION = 31300;8+static const int VERSION = 31400;9 static const char* pszSubVer = "";10 11 12@@ -725,39 +725,39 @@13     typedef vector_type::const_iterator   const_iterator;14     typedef vector_type::reverse_iterator reverse_iterator;15 16-    explicit CDataStream(int nTypeIn=0, int nVersionIn=VERSION)17+    explicit CDataStream(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)18     {19         Init(nTypeIn, nVersionIn);20     }21 22-    CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=0, int nVersionIn=VERSION) : vch(pbegin, pend)23+    CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)24     {25         Init(nTypeIn, nVersionIn);26     }27 28 #if !defined(_MSC_VER) || _MSC_VER >= 130029-    CDataStream(const char* pbegin, const char* pend, int nTypeIn=0, int nVersionIn=VERSION) : vch(pbegin, pend)30+    CDataStream(const char* pbegin, const char* pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)31     {32         Init(nTypeIn, nVersionIn);33     }34 #endif35 36-    CDataStream(const vector_type& vchIn, int nTypeIn=0, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())37+    CDataStream(const vector_type& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())38     {39         Init(nTypeIn, nVersionIn);40     }41 42-    CDataStream(const vector<char>& vchIn, int nTypeIn=0, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())43+    CDataStream(const vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())44     {45         Init(nTypeIn, nVersionIn);46     }47 48-    CDataStream(const vector<unsigned char>& vchIn, int nTypeIn=0, int nVersionIn=VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])49+    CDataStream(const vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])50     {51         Init(nTypeIn, nVersionIn);52     }53 54-    void Init(int nTypeIn=0, int nVersionIn=VERSION)55+    void Init(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)56     {57         nReadPos = 0;58         nType = nTypeIn;

setup.nsi (modified)

1--- v0.3.13/setup.nsi2+++ v0.3.14/setup.nsi3@@ -7,7 +7,7 @@4 5 # General Symbol Definitions6 !define REGKEY "SOFTWARE\$(^Name)"7-!define VERSION 0.3.138+!define VERSION 0.3.149 !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.13-win32-setup.exe17+OutFile bitcoin-0.3.14-win32-setup.exe18 InstallDir $PROGRAMFILES\Bitcoin19 CRCCheck on20 XPStyle on21 ShowInstDetails show22-VIProductVersion 0.3.13.023+VIProductVersion 0.3.14.024 VIAddVersionKey ProductName Bitcoin25 VIAddVersionKey ProductVersion "${VERSION}"26 VIAddVersionKey CompanyName "${COMPANY}"

ui.cpp (modified)

1--- v0.3.13/ui.cpp2+++ v0.3.14/ui.cpp3@@ -502,10 +502,9 @@4     return nIndex != -1;5 }6 7-string FormatTxStatus(const CWalletTx& wtx, bool& fConfirmed)8+string FormatTxStatus(const CWalletTx& wtx)9 {10     // Status11-    fConfirmed = false;12     if (!wtx.IsFinal())13     {14         if (wtx.nLockTime < 500000000)15@@ -516,8 +515,6 @@16     else17     {18         int nDepth = wtx.GetDepthInMainChain();19-        if (nDepth >= 1 || wtx.GetDebit() > 0)20-            fConfirmed = true;21         if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)22             return strprintf(_("%d/offline?"), nDepth);23         else if (nDepth < 6)24@@ -527,12 +524,6 @@25     }26 }27 28-string FormatTxStatus(const CWalletTx& wtx)29-{30-    bool fConfirmed;31-    return FormatTxStatus(wtx, fConfirmed);32-}33-34 string SingleLine(const string& strIn)35 {36     string strOut;37@@ -561,9 +552,8 @@38     int64 nDebit = wtx.GetDebit();39     int64 nNet = nCredit - nDebit;40     uint256 hash = wtx.GetHash();41-    bool fConfirmed;42-    string strStatus = FormatTxStatus(wtx, fConfirmed);43-    wtx.fConfirmedDisplayed = fConfirmed;44+    string strStatus = FormatTxStatus(wtx);45+    bool fConfirmed = wtx.fConfirmedDisplayed = wtx.IsConfirmed();46     wxColour colour = (fConfirmed ? wxColour(0,0,0) : wxColour(128,128,128));47     map<string, string> mapValue = wtx.mapValue;48     wtx.nLinesDisplayed = 1;49@@ -773,6 +763,7 @@50                            SingleLine(strDescription),51                            FormatMoney(-nValue, true),52                            "");53+                nIndex = -1;54                 wtx.nLinesDisplayed++;55             }56         }57@@ -914,16 +905,16 @@58                 continue;59             }60             CWalletTx& wtx = (*mi).second;61-            bool fConfirmed;62-            string strStatus = FormatTxStatus(wtx, fConfirmed);63-            if (wtx.IsCoinBase() || wtx.GetTxTime() != wtx.nTimeDisplayed || fConfirmed != wtx.fConfirmedDisplayed)64+            if (wtx.IsCoinBase() ||65+                wtx.GetTxTime() != wtx.nTimeDisplayed ||66+                wtx.IsConfirmed() != wtx.fConfirmedDisplayed)67             {68                 if (!InsertTransaction(wtx, false, nIndex))69                     m_listCtrl->DeleteItem(nIndex--);70             }71             else72             {73-                m_listCtrl->SetItem(nIndex, 2, strStatus);74+                m_listCtrl->SetItem(nIndex, 2, FormatTxStatus(wtx));75             }76         }77     }78@@ -1180,7 +1171,7 @@79     string strName = dialog.GetValue();80 81     // Generate new key82-    string strAddress = PubKeyToAddress(GenerateNewKey());83+    string strAddress = PubKeyToAddress(CWalletDB().GetKeyFromKeyPool());84 85     // Save86     SetAddressBookName(strAddress, strName);87@@ -1435,7 +1426,10 @@88                 if (txout.IsMine())89                     strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";90 91-            strHTML += "<b>Inputs:</b><br>";92+            strHTML += "<br><b>Transaction:</b><br>";93+            strHTML += HtmlEscape(wtx.ToString(), true);94+95+            strHTML += "<br><b>Inputs:</b><br>";96             CRITICAL_BLOCK(cs_mapWallet)97             {98                 foreach(const CTxIn& txin, wtx.vin)99@@ -1454,9 +1448,6 @@100                     }101                 }102             }103-104-            strHTML += "<br><hr><br><b>Transaction:</b><br>";105-            strHTML += HtmlEscape(wtx.ToString(), true);106         }107 108 109@@ -2255,9 +2246,9 @@110             Error(_("Insufficient funds"));111             return;112         }113-        CKey key;114+        CReserveKey reservekey;115         int64 nFeeRequired;116-        if (!CreateTransaction(scriptPubKey, nPrice, wtx, key, nFeeRequired))117+        if (!CreateTransaction(scriptPubKey, nPrice, wtx, reservekey, nFeeRequired))118         {119             if (nPrice + nFeeRequired > GetBalance())120                 Error(strprintf(_("This is an oversized transaction that requires a transaction fee of %s"), FormatMoney(nFeeRequired).c_str()));121@@ -2297,7 +2288,7 @@122             return;123 124         // Commit125-        if (!CommitTransaction(wtx, key))126+        if (!CommitTransaction(wtx, reservekey))127         {128             Error(_("The transaction was rejected.  This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."));129             return;130@@ -2575,7 +2566,7 @@131         strName = dialog.GetValue();132 133         // Generate new key134-        strAddress = PubKeyToAddress(GenerateNewKey());135+        strAddress = PubKeyToAddress(CWalletDB().GetKeyFromKeyPool());136     }137 138     // Add to list and select it

util.cpp (modified)

1--- v0.3.13/util.cpp2+++ v0.3.14/util.cpp3@@ -16,6 +16,7 @@4 bool fDaemon = false;5 bool fCommandLine = false;6 string strMiscWarning;7+bool fTestNet = false;8 9 10 11@@ -572,7 +573,7 @@12     strMiscWarning = pszMessage;13 #ifdef GUI14     if (wxTheApp && !fDaemon)15-        boost::thread(bind(ThreadOneMessageBox, string(pszMessage)));16+        boost::thread(boost::bind(ThreadOneMessageBox, string(pszMessage)));17 #endif18 }19 20@@ -649,15 +650,11 @@21 void GetDataDir(char* pszDir)22 {23     // pszDir must be at least MAX_PATH length.24+    int nVariation;25     if (pszSetDataDir[0] != 0)26     {27         strlcpy(pszDir, pszSetDataDir, MAX_PATH);28-        static bool fMkdirDone;29-        if (!fMkdirDone)30-        {31-            fMkdirDone = true;32-            filesystem::create_directory(pszDir);33-        }34+        nVariation = 0;35     }36     else37     {38@@ -665,11 +662,23 @@39         // value so we don't have to do memory allocations after that.40         static char pszCachedDir[MAX_PATH];41         if (pszCachedDir[0] == 0)42-        {43             strlcpy(pszCachedDir, GetDefaultDataDir().c_str(), sizeof(pszCachedDir));44-            filesystem::create_directory(pszCachedDir);45-        }46         strlcpy(pszDir, pszCachedDir, MAX_PATH);47+        nVariation = 1;48+    }49+    if (fTestNet)50+    {51+        char* p = pszDir + strlen(pszDir);52+        if (p > pszDir && p[-1] != '/' && p[-1] != '\\')53+            *p++ = '/';54+        strcpy(p, "testnet");55+        nVariation += 2;56+    }57+    static bool pfMkdir[4];58+    if (!pfMkdir[nVariation])59+    {60+        pfMkdir[nVariation] = true;61+        filesystem::create_directory(pszDir);62     }63 }64 65@@ -807,7 +816,7 @@66                 string strMessage = _("Warning: Please check that your computer's date and time are correct.  If your clock is wrong Bitcoin will not work properly.");67                 strMiscWarning = strMessage;68                 printf("*** %s\n", strMessage.c_str());69-                boost::thread(bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));70+                boost::thread(boost::bind(ThreadSafeMessageBox, strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION, (wxWindow*)NULL, -1, -1));71             }72         }73         foreach(int64 n, vTimeOffsets)

util.h (modified)

1--- v0.3.13/util.h2+++ v0.3.14/util.h3@@ -145,6 +145,7 @@4 extern bool fDaemon;5 extern bool fCommandLine;6 extern string strMiscWarning;7+extern bool fTestNet;8 9 void RandAddSeed();10 void RandAddSeedPerfmon();11@@ -622,3 +623,27 @@12 }13 #endif14 15+16+17+18+19+inline bool AffinityBugWorkaround(void(*pfn)(void*))20+{21+#ifdef __WXMSW__22+    // Sometimes after a few hours affinity gets stuck on one processor23+    DWORD dwProcessAffinityMask = -1;24+    DWORD dwSystemAffinityMask = -1;25+    GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinityMask, &dwSystemAffinityMask);26+    DWORD dwPrev1 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);27+    DWORD dwPrev2 = SetThreadAffinityMask(GetCurrentThread(), dwProcessAffinityMask);28+    if (dwPrev2 != dwProcessAffinityMask)29+    {30+        printf("AffinityBugWorkaround() : SetThreadAffinityMask=%d, ProcessAffinityMask=%d, restarting thread\n", dwPrev2, dwProcessAffinityMask);31+        if (!CreateThread(pfn, NULL))32+            printf("Error: CreateThread() failed\n");33+        return true;34+    }35+#endif36+    return false;37+}38+
0:000:00