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.2 → v0.3.3

19 files · +411 · −115 · 40cd03694 · 2010-07-26 · Satoshi Nakamoto

Release commit message: Gavin Andresen's JSON-RPC HTTP authentication, faster initial block download -- version 0.3.3

Previous diff: v0.3.1 → v0.3.2. Next: v0.3.3 → v0.3.6.

bugs.txt (removed)

1--- v0.3.2/bugs.txt2+++ /dev/null3@@ -1,2 +1 @@4-Known bugs:5-- Window flickers when blocks are added (problem with repainting?)6+

changelog.txt (removed)

1--- v0.3.2/changelog.txt2+++ /dev/null3@@ -1,7 +1 @@4-Changes after 0.1.5:5---------------------6-+ Options dialog layout changed - added the UI options panel7-+ Minimize to tray feature8-+ Startup on system boot feature9-+ Ask before closing10-+ NSIS installer11+

db.cpp (modified)

1--- v0.3.2/db.cpp2+++ v0.3.3/db.cpp3@@ -130,7 +130,14 @@4         vTxn.front()->abort();5     vTxn.clear();6     pdb = NULL;7-    dbenv.txn_checkpoint(0, 0, 0);8+9+    // Flush database activity from memory pool to disk log10+    unsigned int nMinutes = 0;11+    if (strFile == "addr.dat")12+        nMinutes = 2;13+    if (strFile == "blkindex.dat" && IsInitialBlockDownload() && nBestHeight % 500 != 0)14+        nMinutes = 1;15+    dbenv.txn_checkpoint(0, nMinutes, 0);16 17     CRITICAL_BLOCK(cs_db)18         --mapFileUseCount[strFile];19@@ -357,11 +364,12 @@20 21 bool CTxDB::LoadBlockIndex()22 {23-    // Get cursor24+    // Get database cursor25     Dbc* pcursor = GetCursor();26     if (!pcursor)27         return false;28 29+    // Load mapBlockIndex30     unsigned int fFlags = DB_SET_RANGE;31     loop32     {33@@ -398,7 +406,7 @@34             pindexNew->nBits          = diskindex.nBits;35             pindexNew->nNonce         = diskindex.nNonce;36 37-            // Watch for genesis block and best block38+            // Watch for genesis block39             if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)40                 pindexGenesisBlock = pindexNew;41         }42@@ -409,17 +417,33 @@43     }44     pcursor->close();45 46+    // Calculate bnChainWork47+    vector<pair<int, CBlockIndex*> > vSortedByHeight;48+    vSortedByHeight.reserve(mapBlockIndex.size());49+    foreach(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)50+    {51+        CBlockIndex* pindex = item.second;52+        vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));53+    }54+    sort(vSortedByHeight.begin(), vSortedByHeight.end());55+    foreach(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)56+    {57+        CBlockIndex* pindex = item.second;58+        pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();59+    }60+61+    // Load hashBestChain pointer to end of best chain62     if (!ReadHashBestChain(hashBestChain))63     {64         if (pindexGenesisBlock == NULL)65             return true;66-        return error("CTxDB::LoadBlockIndex() : hashBestChain not found");67-    }68-69+        return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");70+    }71     if (!mapBlockIndex.count(hashBestChain))72-        return error("CTxDB::LoadBlockIndex() : blockindex for hashBestChain not found");73+        return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");74     pindexBest = mapBlockIndex[hashBestChain];75     nBestHeight = pindexBest->nHeight;76+    bnBestChainWork = pindexBest->bnChainWork;77     printf("LoadBlockIndex(): hashBestChain=%s  height=%d\n", hashBestChain.ToString().substr(0,16).c_str(), nBestHeight);78 79     return true;

db.h (modified)

1--- v0.3.2/db.h2+++ v0.3.3/db.h3@@ -16,7 +16,7 @@4 extern CCriticalSection cs_mapAddressBook;5 extern vector<unsigned char> vchDefaultKey;6 extern bool fClient;7-8+extern int nBestHeight;9 10 11 extern unsigned int nWalletDBUpdated;12@@ -210,7 +210,7 @@13         if (!pdb)14             return false;15         DbTxn* ptxn = NULL;16-        int ret = dbenv.txn_begin(GetTxn(), &ptxn, 0);17+        int ret = dbenv.txn_begin(GetTxn(), &ptxn, DB_TXN_NOSYNC);18         if (!ptxn || ret != 0)19             return false;20         vTxn.push_back(ptxn);

headers.h (modified)

1--- v0.3.2/headers.h2+++ v0.3.3/headers.h3@@ -26,6 +26,7 @@4 #include <wx/clipbrd.h>5 #include <wx/taskbar.h>6 #endif7+#include <openssl/buffer.h>8 #include <openssl/ecdsa.h>9 #include <openssl/evp.h>10 #include <openssl/rand.h>11@@ -64,6 +65,9 @@12 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>13 #include <boost/date_time/gregorian/gregorian_types.hpp>14 #include <boost/date_time/posix_time/posix_time_types.hpp>15+#include <boost/config.hpp>16+#include <boost/program_options/detail/config_file.hpp>17+#include <boost/program_options/parsers.hpp>18 19 #ifdef __WXMSW__20 #include <windows.h>

init.cpp (modified)

1--- v0.3.2/init.cpp2+++ v0.3.3/init.cpp3@@ -240,33 +240,34 @@4 5 bool CMyApp::Initialize(int& argc, wxChar** argv)6 {7-    if (argc > 1 && argv[1][0] != '-' && (!fWindows || argv[1][0] != '/') &&8-        wxString(argv[1]) != "start")9-    {10-        fCommandLine = true;11-    }12-    else if (!fGUI)13-    {14-        fDaemon = true;15-    }16-    else17-    {18-        // wxApp::Initialize will remove environment-specific parameters,19-        // so it's too early to call ParseParameters yet20-        for (int i = 1; i < argc; i++)21-        {22-            wxString str = argv[i];23-            #ifdef __WXMSW__24-            if (str.size() >= 1 && str[0] == '/')25-                str[0] = '-';26-            char pszLower[MAX_PATH];27-            strlcpy(pszLower, str.c_str(), sizeof(pszLower));28-            strlwr(pszLower);29-            str = pszLower;30-            #endif31-            // haven't decided which argument to use for this yet32-            if (str == "-daemon" || str == "-d" || str == "start")33-                fDaemon = true;34+    for (int i = 1; i < argc; i++)35+        if (!IsSwitchChar(argv[i][0]))36+            fCommandLine = true;37+38+    if (!fCommandLine)39+    {40+        if (!fGUI)41+        {42+            fDaemon = true;43+        }44+        else45+        {46+            // wxApp::Initialize will remove environment-specific parameters,47+            // so it's too early to call ParseParameters yet48+            for (int i = 1; i < argc; i++)49+            {50+                wxString str = argv[i];51+                #ifdef __WXMSW__52+                if (str.size() >= 1 && str[0] == '/')53+                    str[0] = '-';54+                char pszLower[MAX_PATH];55+                strlcpy(pszLower, str.c_str(), sizeof(pszLower));56+                strlwr(pszLower);57+                str = pszLower;58+                #endif59+                if (str == "-daemon")60+                    fDaemon = true;61+            }62         }63     }64 65@@ -375,22 +376,23 @@66     //67     // Parameters68     //69-    if (fCommandLine)70-    {71-        int ret = CommandLineRPC(argc, argv);72-        exit(ret);73-    }74-75     ParseParameters(argc, argv);76+77+    if (mapArgs.count("-datadir"))78+        strlcpy(pszSetDataDir, mapArgs["-datadir"].c_str(), sizeof(pszSetDataDir));79+80+    ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir81+82     if (mapArgs.count("-?") || mapArgs.count("--help"))83     {84         wxString strUsage = string() +85           _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +86-            "  bitcoin [options]       \t" + "\n" +87-            "  bitcoin [command]       \t" + _("Send command to bitcoin running with -server or -daemon\n") +88-            "  bitcoin [command] -?    \t" + _("Get help for a command\n") +89-            "  bitcoin help            \t" + _("List commands\n") +90+            "  bitcoin [options]                   \t  " + "\n" +91+            "  bitcoin [options] <command> [params]\t  " + _("Send command to -server or bitcoind\n") +92+            "  bitcoin [options] <command> -?      \t\t  " + _("Get help for a command\n") +93+            "  bitcoin help                        \t\t\t  " + _("List commands\n") +94           _("Options:\n") +95+            "  -conf=<file>    \t  " + _("Specify configuration file (default: bitcoin.conf)\n") +96             "  -gen            \t  " + _("Generate coins\n") +97             "  -gen=0          \t  " + _("Don't generate coins\n") +98             "  -min            \t  " + _("Start minimized\n") +99@@ -413,14 +415,17 @@100         return false;101     }102 103-    if (mapArgs.count("-datadir"))104-        strlcpy(pszSetDataDir, mapArgs["-datadir"].c_str(), sizeof(pszSetDataDir));105-106     if (mapArgs.count("-debug"))107         fDebug = true;108 109     if (mapArgs.count("-printtodebugger"))110         fPrintToDebugger = true;111+112+    if (fCommandLine)113+    {114+        int ret = CommandLineRPC(argc, argv);115+        exit(ret);116+    }117 118     if (!fDebug && !pszSetDataDir[0])119         ShrinkDebugFile();

main.cpp (modified)

1--- v0.3.2/main.cpp2+++ v0.3.3/main.cpp3@@ -24,6 +24,7 @@4 const uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");5 CBlockIndex* pindexGenesisBlock = NULL;6 int nBestHeight = -1;7+CBigNum bnBestChainWork = 0;8 uint256 hashBestChain = 0;9 CBlockIndex* pindexBest = NULL;10 int64 nTimeBestReceived = 0;11@@ -848,6 +849,23 @@12     return bnNew.GetCompact();13 }14 15+vector<int> vStartingHeight;16+void AddStartingHeight(int nStartingHeight)17+{18+    if (nStartingHeight != -1)19+    {20+        vStartingHeight.push_back(nStartingHeight);21+        sort(vStartingHeight.begin(), vStartingHeight.end());22+    }23+}24+25+bool IsInitialBlockDownload()26+{27+    int nMedian = 69000;28+    if (vStartingHeight.size() >= 5)29+        nMedian = vStartingHeight[vStartingHeight.size()/2];30+    return nBestHeight < nMedian-1000;31+}32 33 34 35@@ -1208,13 +1226,14 @@36         pindexNew->pprev = (*miPrev).second;37         pindexNew->nHeight = pindexNew->pprev->nHeight + 1;38     }39+    pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();40 41     CTxDB txdb;42     txdb.TxnBegin();43     txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));44 45     // New best46-    if (pindexNew->nHeight > nBestHeight)47+    if (pindexNew->bnChainWork > bnBestChainWork)48     {49         if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)50         {51@@ -1253,6 +1272,7 @@52         hashBestChain = hash;53         pindexBest = pindexNew;54         nBestHeight = pindexBest->nHeight;55+        bnBestChainWork = pindexNew->bnChainWork;56         nTimeBestReceived = GetTime();57         nTransactionsUpdated++;58         printf("AddToBlockIndex: new best=%s  height=%d\n", hashBestChain.ToString().substr(0,16).c_str(), nBestHeight);59@@ -1900,6 +1920,7 @@60         }61 62         AddTimeData(pfrom->addr.ip, nTime);63+        AddStartingHeight(pfrom->nStartingHeight);64 65         // Change version66         if (pfrom->nVersion >= 209)67@@ -2845,6 +2866,10 @@68 }69 70 71+int GetRandInt(int nMax)72+{73+    return GetRand(nMax);74+}75 76 bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)77 {78@@ -2858,9 +2883,14 @@79 80     CRITICAL_BLOCK(cs_mapWallet)81     {82-        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)83-        {84-            CWalletTx* pcoin = &(*it).second;85+       vector<CWalletTx*> vCoins;86+       vCoins.reserve(mapWallet.size());87+       for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)88+           vCoins.push_back(&(*it).second);89+       random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);90+91+       foreach(CWalletTx* pcoin, vCoins)92+       {93             if (!pcoin->IsFinal() || pcoin->fSpent)94                 continue;95             int64 n = pcoin->GetCredit();

main.h (modified)

1--- v0.3.2/main.h2+++ v0.3.3/main.h3@@ -32,6 +32,7 @@4 extern const uint256 hashGenesisBlock;5 extern CBlockIndex* pindexGenesisBlock;6 extern int nBestHeight;7+extern CBigNum bnBestChainWork;8 extern uint256 hashBestChain;9 extern CBlockIndex* pindexBest;10 extern unsigned int nTransactionsUpdated;11@@ -78,6 +79,7 @@12 void GenerateBitcoins(bool fGenerate);13 void ThreadBitcoinMiner(void* parg);14 void BitcoinMiner();15+bool IsInitialBlockDownload();16 17 18 19@@ -986,11 +988,14 @@20 21         // Flush stdio buffers and commit to disk before returning22         fflush(fileout);23+        if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)24+        {25 #ifdef __WXMSW__26-        _commit(_fileno(fileout));27+            _commit(_fileno(fileout));28 #else29-        fsync(fileno(fileout));30+            fsync(fileno(fileout));31 #endif32+        }33 34         return true;35     }36@@ -1072,6 +1077,7 @@37     unsigned int nFile;38     unsigned int nBlockPos;39     int nHeight;40+    CBigNum bnChainWork;41 42     // block header43     int nVersion;44@@ -1089,6 +1095,7 @@45         nFile = 0;46         nBlockPos = 0;47         nHeight = 0;48+        bnChainWork = 0;49 50         nVersion       = 0;51         hashMerkleRoot = 0;52@@ -1105,6 +1112,7 @@53         nFile = nFileIn;54         nBlockPos = nBlockPosIn;55         nHeight = 0;56+        bnChainWork = 0;57 58         nVersion       = block.nVersion;59         hashMerkleRoot = block.hashMerkleRoot;60@@ -1116,6 +1124,11 @@61     uint256 GetBlockHash() const62     {63         return *phashBlock;64+    }65+66+    CBigNum GetBlockWork() const67+    {68+        return (CBigNum(1)<<256) / (CBigNum().SetCompact(nBits)+1);69     }70 71     bool IsInMainChain() const

makefile.mingw (modified)

1--- v0.3.2/makefile.mingw2+++ v0.3.3/makefile.mingw3@@ -22,7 +22,7 @@4  -l wxmsw29ud_html -l wxmsw29ud_core -l wxmsw29ud_adv -l wxbase29ud -l wxtiffd -l wxjpegd -l wxpngd -l wxzlibd5 6 LIBS= \7- -l libboost_system-mgw34-mt-d -l libboost_filesystem-mgw34-mt-d \8+ -l libboost_system-mgw34-mt-d -l libboost_filesystem-mgw34-mt-d -l libboost_program_options-mgw34-mt-d \9  -l db_cxx \10  -l eay32 \11  -l kernel32 -l user32 -l gdi32 -l comdlg32 -l winspool -l winmm -l shell32 -l comctl32 -l ole32 -l oleaut32 -l uuid -l rpcrt4 -l advapi32 -l ws2_32 -l shlwapi

makefile.osx (modified)

1--- v0.3.2/makefile.osx2+++ v0.3.3/makefile.osx3@@ -19,6 +19,7 @@4  $(DEPSDIR)/lib/libdb_cxx-4.8.a \5  $(DEPSDIR)/lib/libboost_system.a \6  $(DEPSDIR)/lib/libboost_filesystem.a \7+ $(DEPSDIR)/lib/libboost_program_options.a \8  $(DEPSDIR)/lib/libcrypto.a 9 10 WXDEFS=$(shell $(DEPSDIR)/bin/wx-config --cxxflags) -DNOPCH -DMSG_NOSIGNAL=0

makefile.unix (modified)

1--- v0.3.2/makefile.unix2+++ v0.3.3/makefile.unix3@@ -21,7 +21,7 @@4 5 LIBS= \6  -Wl,-Bstatic \7-   -l boost_system -l boost_filesystem \8+   -l boost_system -l boost_filesystem -l boost_program_options \9    -l db_cxx \10    -l crypto \11  -Wl,-Bdynamic \

makefile.vc (modified)

1--- v0.3.2/makefile.vc2+++ v0.3.3/makefile.vc3@@ -19,7 +19,7 @@4   /LIBPATH:"/wxwidgets/lib/vc_lib"5 6 LIBS= \7-  libboost_system-vc80-mt-gd.lib libboost_filesystem-vc80-mt-gd.lib \8+  libboost_system-vc80-mt-gd.lib libboost_filesystem-vc80-mt-gd.lib libboost_program_options-vc80-mt-gd.lib \9   libdb47sd.lib \10   libeay32.lib \11   wxmsw29ud_html.lib wxmsw29ud_core.lib wxmsw29ud_adv.lib wxbase29ud.lib wxtiffd.lib wxjpegd.lib wxpngd.lib wxzlibd.lib \

rpc.cpp (modified)

1--- v0.3.2/rpc.cpp2+++ v0.3.3/rpc.cpp3@@ -23,6 +23,28 @@4 5 6 7+void PrintConsole(const char* format, ...)8+{9+    char buffer[50000];10+    int limit = sizeof(buffer);11+    va_list arg_ptr;12+    va_start(arg_ptr, format);13+    int ret = _vsnprintf(buffer, limit, format, arg_ptr);14+    va_end(arg_ptr);15+    if (ret < 0 || ret >= limit)16+    {17+        ret = limit - 1;18+        buffer[limit-1] = 0;19+    }20+#if defined(__WXMSW__) && wxUSE_GUI21+    MyMessageBox(buffer, "Bitcoin", wxOK | wxICON_EXCLAMATION);22+#else23+    fprintf(stdout, "%s", buffer);24+#endif25+}26+27+28+29 30 31 32@@ -32,7 +54,6 @@33 ///34 35 36-37 Value help(const Array& params, bool fHelp)38 {39     if (fHelp || params.size() != 0)40@@ -41,12 +62,20 @@41             "List commands.");42 43     string strRet;44+    set<rpcfn_type> setDone;45     for (map<string, rpcfn_type>::iterator mi = mapCallTable.begin(); mi != mapCallTable.end(); ++mi)46     {47+        string strMethod = (*mi).first;48+        // We already filter duplicates, but these deprecated screw up the sort order49+        if (strMethod == "getamountreceived" ||50+            strMethod == "getallreceived")51+            continue;52         try53         {54             Array params;55-            (*(*mi).second)(params, true);56+            rpcfn_type pfn = (*mi).second;57+            if (setDone.insert(pfn).second)58+                (*pfn)(params, true);59         }60         catch (std::exception& e)61         {62@@ -603,7 +632,6 @@63     make_pair("getlabel",              &getlabel),64     make_pair("getaddressesbylabel",   &getaddressesbylabel),65     make_pair("sendtoaddress",         &sendtoaddress),66-    make_pair("listtransactions",      &listtransactions),67     make_pair("getamountreceived",     &getreceivedbyaddress), // deprecated, renamed to getreceivedbyaddress68     make_pair("getallreceived",        &listreceivedbyaddress), // deprecated, renamed to listreceivedbyaddress69     make_pair("getreceivedbyaddress",  &getreceivedbyaddress),70@@ -623,23 +651,41 @@71 // and to be compatible with other JSON-RPC implementations.72 //73 74-string HTTPPost(const string& strMsg)75-{76-    return strprintf(77-            "POST / HTTP/1.1\r\n"78-            "User-Agent: json-rpc/1.0\r\n"79-            "Host: 127.0.0.1\r\n"80-            "Content-Type: application/json\r\n"81-            "Content-Length: %d\r\n"82-            "Accept: application/json\r\n"83+string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)84+{85+    ostringstream s;86+    s << "POST / HTTP/1.1\r\n"87+      << "User-Agent: json-rpc/1.0\r\n"88+      << "Host: 127.0.0.1\r\n"89+      << "Content-Type: application/json\r\n"90+      << "Content-Length: " << strMsg.size() << "\r\n"91+      << "Accept: application/json\r\n";92+    for (map<string,string>::const_iterator it = mapRequestHeaders.begin(); it != mapRequestHeaders.end(); ++it)93+        s << it->first << ": " << it->second << "\r\n";94+    s << "\r\n" << strMsg;95+96+    return s.str();97+}98+99+string HTTPReply(const string& strMsg, int nStatus=200)100+{101+    if (nStatus == 401)102+        return "HTTP/1.0 401 Authorization Required\r\n"103+            "Server: HTTPd/1.0\r\n"104+            "Date: Sat, 08 Jul 2006 12:04:08 GMT\r\n"105+            "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"106+            "Content-Type: text/html\r\n"107+            "Content-Length: 311\r\n"108             "\r\n"109-            "%s",110-        strMsg.size(),111-        strMsg.c_str());112-}113-114-string HTTPReply(const string& strMsg, int nStatus=200)115-{116+            "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"117+            "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"118+            "<HTML>\r\n"119+            "<HEAD>\r\n"120+            "<TITLE>Error</TITLE>\r\n"121+            "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"122+            "</HEAD>\r\n"123+            "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"124+            "</HTML>\r\n";125     string strStatus;126     if (nStatus == 200) strStatus = "OK";127     if (nStatus == 500) strStatus = "Internal Server Error";128@@ -658,7 +704,17 @@129         strMsg.c_str());130 }131 132-int ReadHTTPHeader(tcp::iostream& stream)133+int ReadHTTPStatus(tcp::iostream& stream)134+{135+    string str;136+    getline(stream, str);137+    vector<string> vWords;138+    boost::split(vWords, str, boost::is_any_of(" "));139+    int nStatus = atoi(vWords[1].c_str());140+    return nStatus;141+}142+143+int ReadHTTPHeader(tcp::iostream& stream, map<string, string>& mapHeadersRet)144 {145     int nLen = 0;146     loop147@@ -667,26 +723,92 @@148         std::getline(stream, str);149         if (str.empty() || str == "\r")150             break;151-        if (str.substr(0,15) == "Content-Length:")152-            nLen = atoi(str.substr(15));153+        string::size_type nColon = str.find(":");154+        if (nColon != string::npos)155+        {156+            string strHeader = str.substr(0, nColon);157+            boost::trim(strHeader);158+            string strValue = str.substr(nColon+1);159+            boost::trim(strValue);160+            mapHeadersRet[strHeader] = strValue;161+            if (strHeader == "Content-Length")162+                nLen = atoi(strValue.c_str());163+        }164     }165     return nLen;166 }167 168-inline string ReadHTTP(tcp::iostream& stream)169-{170+int ReadHTTP(tcp::iostream& stream, map<string, string>& mapHeadersRet, string& strMessageRet)171+{172+    mapHeadersRet.clear();173+    strMessageRet = "";174+175+    // Read status176+    int nStatus = ReadHTTPStatus(stream);177+178     // Read header179-    int nLen = ReadHTTPHeader(stream);180+    int nLen = ReadHTTPHeader(stream, mapHeadersRet);181     if (nLen <= 0)182-        return string();183+        return 500;184 185     // Read message186     vector<char> vch(nLen);187     stream.read(&vch[0], nLen);188-    return string(vch.begin(), vch.end());189-}190-191-192+    strMessageRet = string(vch.begin(), vch.end());193+194+    return nStatus;195+}196+197+string EncodeBase64(string s)198+{199+    BIO *b64, *bmem;200+    BUF_MEM *bptr;201+202+    b64 = BIO_new(BIO_f_base64());203+    bmem = BIO_new(BIO_s_mem());204+    b64 = BIO_push(b64, bmem);205+    BIO_write(b64, s.c_str(), s.size());206+    BIO_flush(b64);207+    BIO_get_mem_ptr(b64, &bptr);208+209+    string result(bptr->data, bptr->length-1);210+    BIO_free_all(b64);211+212+    return result;213+}214+215+string DecodeBase64(string s)216+{217+    BIO *b64, *bmem;218+219+    char* buffer = static_cast<char*>(calloc(s.size(), sizeof(char)));220+221+    b64 = BIO_new(BIO_f_base64());222+    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);223+    bmem = BIO_new_mem_buf(const_cast<char*>(s.c_str()), s.size());224+    bmem = BIO_push(b64, bmem);225+    BIO_read(bmem, buffer, s.size());226+    BIO_free_all(bmem);227+228+    string result(buffer);229+    free(buffer);230+    return result;231+}232+233+bool HTTPAuthorized(map<string, string>& mapHeaders)234+{235+    string strAuth = mapHeaders["Authorization"];236+    if (strAuth.substr(0,6) != "Basic ")237+        return false;238+    string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);239+    string strUserPass = DecodeBase64(strUserPass64);240+    string::size_type nColon = strUserPass.find(":");241+    if (nColon == string::npos)242+        return false;243+    string strUser = strUserPass.substr(0, nColon);244+    string strPassword = strUserPass.substr(nColon+1);245+    return (strUser == mapArgs["-rpcuser"] && strPassword == mapArgs["-rpcpassword"]);246+}247 248 //249 // JSON-RPC protocol250@@ -742,6 +864,22 @@251 {252     printf("ThreadRPCServer started\n");253 254+    if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")255+    {256+        string strWhatAmI = "To use bitcoind";257+        if (mapArgs.count("-server"))258+            strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");259+        else if (mapArgs.count("-daemon"))260+            strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");261+        PrintConsole(262+            _("Warning: %s, you must set rpcpassword=<password>\nin the configuration file: %s\n"263+              "If the file does not exist, create it with owner-readable-only file permissions.\n"),264+                strWhatAmI.c_str(),265+                GetConfigFile().c_str());266+        CreateThread(Shutdown, NULL);267+        return;268+    }269+270     // Bind to loopback 127.0.0.1 so the socket can only be accessed locally271     boost::asio::io_service io_service;272     tcp::endpoint endpoint(boost::asio::ip::address_v4::loopback(), 8332);273@@ -763,8 +901,26 @@274             continue;275 276         // Receive request277-        string strRequest = ReadHTTP(stream);278-        printf("ThreadRPCServer request=%s", strRequest.c_str());279+        map<string, string> mapHeaders;280+        string strRequest;281+        ReadHTTP(stream, mapHeaders, strRequest);282+283+        // Check authorization284+        if (mapHeaders.count("Authorization") == 0)285+        {286+            stream << HTTPReply("", 401) << std::flush;287+            continue;288+        }289+        if (!HTTPAuthorized(mapHeaders))290+        {291+            // Deter brute-forcing short passwords292+            if (mapArgs["-rpcpassword"].size() < 15)293+                Sleep(50);294+295+            stream << HTTPReply("", 401) << std::flush;296+            printf("ThreadRPCServer incorrect password attempt\n");297+            continue;298+        }299 300         // Handle multiple invocations per request301         string::iterator begin = strRequest.begin();302@@ -787,6 +943,8 @@303                 const Array& params = find_value(request, "params").get_array();304                 id                  = find_value(request, "id");305 306+                printf("ThreadRPCServer method=%s\n", strMethod.c_str());307+308                 // Execute309                 map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);310                 if (mi == mapCallTable.end())311@@ -814,18 +972,36 @@312 313 Value CallRPC(const string& strMethod, const Array& params)314 {315+    if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")316+        throw runtime_error(strprintf(317+            _("You must set rpcpassword=<password> in the configuration file:\n%s\n"318+              "If the file does not exist, create it with owner-readable-only file permissions."),319+                GetConfigFile().c_str()));320+321     // Connect to localhost322     tcp::iostream stream("127.0.0.1", "8332");323     if (stream.fail())324         throw runtime_error("couldn't connect to server");325 326+    // HTTP basic authentication327+    string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);328+    map<string, string> mapRequestHeaders;329+    mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;330+331     // Send request332     string strRequest = JSONRPCRequest(strMethod, params, 1);333-    stream << HTTPPost(strRequest) << std::flush;334+    string strPost = HTTPPost(strRequest, mapRequestHeaders);335+    stream << strPost << std::flush;336 337     // Receive reply338-    string strReply = ReadHTTP(stream);339-    if (strReply.empty())340+    map<string, string> mapHeaders;341+    string strReply;342+    int nStatus = ReadHTTP(stream, mapHeaders, strReply);343+    if (nStatus == 401)344+        throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");345+    else if (nStatus >= 400 && nStatus != 500)346+        throw runtime_error(strprintf("server returned HTTP error %d", nStatus));347+    else if (strReply.empty())348         throw runtime_error("no response from server");349 350     // Parse reply351@@ -871,7 +1047,14 @@352 {353     try354     {355-        // Check that method exists356+        // Skip switches357+        while (argc > 1 && IsSwitchChar(argv[1][0]))358+        {359+            argc--;360+            argv++;361+        }362+363+        // Check that the method exists364         if (argc < 2)365             throw runtime_error("too few parameters");366         string strMethod = argv[1];

serialize.h (modified)

1--- v0.3.2/serialize.h2+++ v0.3.3/serialize.h3@@ -19,7 +19,7 @@4 class CDataStream;5 class CAutoFile;6 7-static const int VERSION = 302;8+static const int VERSION = 303;9 static const char* pszSubVer = "";10 11 

setup.nsi (modified)

1--- v0.3.2/setup.nsi2+++ v0.3.3/setup.nsi3@@ -7,7 +7,7 @@4 5 # General Symbol Definitions6 !define REGKEY "SOFTWARE\$(^Name)"7-!define VERSION 0.3.28+!define VERSION 0.3.39 !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.2-win32-setup.exe17+OutFile bitcoin-0.3.3-win32-setup.exe18 InstallDir $PROGRAMFILES\Bitcoin19 CRCCheck on20 XPStyle on21 ShowInstDetails show22-VIProductVersion 0.3.2.023+VIProductVersion 0.3.3.024 VIAddVersionKey ProductName Bitcoin25 VIAddVersionKey ProductVersion "${VERSION}"26 VIAddVersionKey CompanyName "${COMPANY}"

ui.cpp (modified)

1--- v0.3.2/ui.cpp2+++ v0.3.3/ui.cpp3@@ -1132,7 +1132,7 @@4     // Ask name5     CGetTextFromUserDialog dialog(this,6         _("New Receiving Address"),7-        _("It's good policy to use a new address for each payment you receive.\n\nLabel"),8+        _("You should use a new address for each payment you receive.\n\nLabel"),9         "");10     if (!dialog.ShowModal())11         return;12@@ -1614,6 +1614,7 @@13 CAboutDialog::CAboutDialog(wxWindow* parent) : CAboutDialogBase(parent)14 {15     m_staticTextVersion->SetLabel(strprintf(_("version %d.%d.%d beta"), VERSION/10000, (VERSION/100)%100, VERSION%100));16+    //m_staticTextVersion->SetLabel(strprintf(_("version %d.%d.%d%s beta"), VERSION/10000, (VERSION/100)%100, VERSION%100, pszSubVer));17 18     // Change (c) into UTF-8 or ANSI copyright symbol19     wxString str = m_staticTextMain->GetLabel();20@@ -2372,7 +2373,7 @@21         // Ask name22         CGetTextFromUserDialog dialog(this,23             _("New Receiving Address"),24-            _("It's good policy to use a new address for each payment you receive.\n\nLabel"),25+            _("You should use a new address for each payment you receive.\n\nLabel"),26             "");27         if (!dialog.ShowModal())28             return;

uibase.h (modified)

1--- v0.3.2/uibase.h2+++ v0.3.3/uibase.h3@@ -227,7 +227,7 @@4 	5 	public:6 		wxStaticText* m_staticTextVersion;7-		CAboutDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("About Bitcoin"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 532,329 ), long style = wxDEFAULT_DIALOG_STYLE );8+		CAboutDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("About Bitcoin"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 532,333 ), long style = wxDEFAULT_DIALOG_STYLE );9 		~CAboutDialogBase();10 	11 };

util.cpp (modified)

1--- v0.3.2/util.cpp2+++ v0.3.3/util.cpp3@@ -416,7 +416,7 @@4 {5     mapArgs.clear();6     mapMultiArgs.clear();7-    for (int i = 0; i < argc; i++)8+    for (int i = 1; i < argc; i++)9     {10         char psz[10000];11         strlcpy(psz, argv[i], sizeof(psz));12@@ -431,6 +431,8 @@13         if (psz[0] == '/')14             psz[0] = '-';15         #endif16+        if (psz[0] != '-')17+            break;18         mapArgs[psz] = pszValue;19         mapMultiArgs[psz].push_back(pszValue);20     }21@@ -619,6 +621,38 @@22     return pszDir;23 }24 25+string GetConfigFile()26+{27+    namespace fs = boost::filesystem;28+    fs::path pathConfig(mapArgs.count("-conf") ? mapArgs["-conf"] : string("bitcoin.conf"));29+    if (!pathConfig.is_complete())30+        pathConfig = fs::path(GetDataDir()) / pathConfig;31+    return pathConfig.string();32+}33+34+void ReadConfigFile(map<string, string>& mapSettingsRet,35+                    map<string, vector<string> >& mapMultiSettingsRet)36+{37+    namespace fs = boost::filesystem;38+    namespace pod = boost::program_options::detail;39+40+    fs::ifstream streamConfig(GetConfigFile());41+    if (!streamConfig.good())42+        return;43+44+    set<string> setOptions;45+    setOptions.insert("*");46+    47+    for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)48+    {49+        // Don't overwrite existing settings so command line settings override bitcoin.conf50+        string strKey = string("-") + it->string_key;51+        if (mapSettingsRet.count(strKey) == 0)52+            mapSettingsRet[strKey] = it->value[0];53+        mapMultiSettingsRet[strKey].push_back(it->value[0]);54+    }55+}56+57 int GetFilesize(FILE* file)58 {59     int nSavePos = ftell(file);60@@ -648,9 +682,6 @@61         }62     }63 }64-65-66-67 68 69 70@@ -701,12 +732,13 @@71         sort(vTimeOffsets.begin(), vTimeOffsets.end());72         int64 nMedian = vTimeOffsets[vTimeOffsets.size()/2];73         nTimeOffset = nMedian;74-        if ((nMedian > 0 ? nMedian : -nMedian) > 5 * 60)75+        if ((nMedian > 0 ? nMedian : -nMedian) > 70 * 60)76         {77             // Only let other nodes change our clock so far before we78             // go to the NTP servers79             /// todo: Get time from NTP servers, then set a flag80             ///    to make sure it doesn't get changed again81+            nTimeOffset = 0;82         }83         foreach(int64 n, vTimeOffsets)84             printf("%+"PRI64d"  ", n);

util.h (modified)

1--- v0.3.2/util.h2+++ v0.3.3/util.h3@@ -141,6 +141,8 @@4 const char* wxGetTranslation(const char* psz);5 int GetFilesize(FILE* file);6 void GetDataDir(char* pszDirRet);7+string GetConfigFile();8+void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet);9 #ifdef __WXMSW__10 string MyGetSpecialFolderPath(int nFolder, bool fCreate);11 #endif12@@ -348,7 +350,14 @@13         ++it;14 }15 16-17+inline bool IsSwitchChar(char c)18+{19+#ifdef __WXMSW__20+    return c == '-' || c == '/';21+#else22+    return c == '-';23+#endif24+}25 26 27 
0:000:00