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.20 → v0.3.21

23 files · +1,253 · −601 · 64ad448ad · 2011-04-20 · Gavin Andresen

Release commit message: Better wording for transaction fee notification messages

Previous diff: r202 → v0.3.20. Next: v0.3.21 → v0.3.22.

build-msw.txt (modified)

1--- v0.3.20/build-msw.txt2+++ v0.3.21/build-msw.txt3@@ -3,7 +3,8 @@4 file license.txt or http://www.opensource.org/licenses/mit-license.php.5 This product includes software developed by the OpenSSL Project for use in6 the OpenSSL Toolkit (http://www.openssl.org/).  This product includes7-cryptographic software written by Eric Young (eay@cryptsoft.com).8+cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP9+software written by Thomas Bernard.10 11 12 WINDOWS BUILD NOTES13@@ -25,23 +26,26 @@14 ------------15 Libraries you need to download separately and build:16 17-                default path  download18-wxWidgets       \wxwidgets-2.9.1-mgw   http://www.wxwidgets.org/downloads/19-OpenSSL         \openssl-1.0.0c-mgw    http://www.openssl.org/source/20-Berkeley DB     \db-4.7.25.NC-mgw      http://www.oracle.com/technology/software/products/berkeley-db/index.html21-Boost           \boost-1.43.0-mgw      http://www.boost.org/users/download/22+                default path               download23+wxWidgets       \wxwidgets-2.9.1-mgw       http://www.wxwidgets.org/downloads/24+OpenSSL         \openssl-1.0.0c-mgw        http://www.openssl.org/source/25+Berkeley DB     \db-4.7.25.NC-mgw          http://www.oracle.com/technology/software/products/berkeley-db/index.html26+Boost           \boost-1.43.0-mgw          http://www.boost.org/users/download/27+miniupnpc       \upnpc-exe-win32-20110215  http://miniupnp.tuxfamily.org/files/28 29 Their licenses:30 wxWidgets      LGPL 2.1 with very liberal exceptions31 OpenSSL        Old BSD license with the problematic advertising requirement32 Berkeley DB    New BSD license with additional requirement that linked software must be free open source33 Boost          MIT-like license34+miniupnpc      New (3-clause) BSD license35 36 Versions used in this release:37 wxWidgets    2.9.138 OpenSSL      1.0.0c39 Berkeley DB  4.7.25.NC40 Boost        1.43.041+miniupnpc    1.5-2011021542 43 44 Notes45@@ -90,6 +94,15 @@46 building with boost 1.45.0 failed because of boost ticket 4614, 425847 builds fine with boost 1.43.048 49+MiniUPnPc50+---------51+Building miniupnpc failed on Windows Server 2003, thus it is expected that a binary copy will be used.52+See http://miniupnp.tuxfamily.org/forum/viewtopic.php?t=64253+UPnP support is optional, make with USE_UPNP= to disable it.54+55+Get upnpc-exe-win32-20110215.zip and unzip it to \upnpc-exe-win32-2011021556+Get miniupnpc-1.5.20110215.tar.gz and copy *.h to \upnpc-exe-win32-20110215\miniupnpc57+58 Bitcoin59 -------60 DOS prompt:

build-osx.txt (modified)

1--- v0.3.20/build-osx.txt2+++ v0.3.21/build-osx.txt3@@ -3,7 +3,8 @@4 file license.txt or http://www.opensource.org/licenses/mit-license.php.5 This product includes software developed by the OpenSSL Project for use in6 the OpenSSL Toolkit (http://www.openssl.org/).  This product includes7-cryptographic software written by Eric Young (eay@cryptsoft.com).8+cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP9+software written by Thomas Bernard.10 11 12 Mac OS X build instructions13@@ -58,7 +59,10 @@14 tar xvjf ~/Downloads/boost_1_42_0.tar.bz215 cd boost_1_42_016 ./bootstrap.sh17-./bjam architecture=combined address-model=32_64 macosx-version=10.6 macosx-version-min=10.5 link=static runtime-link=static --toolset=darwin --prefix=/Users/macosuser/bitcoin/deps install18+./bjam architecture=combined address-model=32_64 macosx-version=10.5 macosx-version-min=10.5 link=static runtime-link=static --toolset=darwin --prefix=/Users/macosuser/bitcoin/deps install19+20+If you're using Snow Leopard, you will need to specify 10.6 as your Mac OS X21+version instead of 10.5.22 23 This part takes a while.. use your judgement and fix it if something doesn't24 build for some reason.25@@ -89,12 +93,12 @@26 mv openssl-1.0.0 openssl-1.0.0-x86_6427 # build i386 (32 bit intel) binary28 cd openssl-1.0.0-i38629-./Configure --prefix=/Users/macosuser/bitcoin/deps --openssldir=/Users/macosuser/deps/openssl darwin-i386-cc && make30+./Configure --prefix=/Users/macosuser/bitcoin/deps --openssldir=/Users/macosuser/bitcoin/deps/openssl darwin-i386-cc && make31 make install # only do this on one of the architectures, to install the headers32 cd ..33 # build x86_64 (64 bit intel) binary34 cd openssl-1.0.0-x86_6435-./Configure --prefix=/Users/macosuser/bitcoin/deps --openssldir=/Users/macosuser/deps/openssl darwin64-x86_64-cc && make36+./Configure --prefix=/Users/macosuser/bitcoin/deps --openssldir=/Users/macosuser/bitcoin/deps/openssl darwin64-x86_64-cc && make37 cd ..38 39 # combine the libs40@@ -108,9 +112,49 @@41 42 output should look like this:43 44-ib/libcrypto.a: Mach-O universal binary with 2 architectures45+lib/libcrypto.a: Mach-O universal binary with 2 architectures46 lib/libcrypto.a (for architecture i386):	current ar archive random library47 lib/libcrypto.a (for architecture x86_64):	current ar archive random library48+49+50+miniupnpc51+---------52+53+The process for miniupnpc (optional) is similar to that of OpenSSL.54+55+Download from http://miniupnp.tuxfamily.org/files/.56+57+cd ~/bitcoin/deps58+tar xvf ~/Downloads/miniupnpc-1.5.tar59+mv miniupnpc-1.5 miniupnpc-1.5-x86_6460+tar xvf ~/Downloads/miniupnpc-1.5.tar61+mv miniupnpc-1.5 miniupnpc-1.5-i38662+# build x86_64 (64 bit intel) binary63+cd miniupnpc-1.5-x86_6464+export CFLAGS="-arch x86_64"65+export LDFLAGS="-arch x86_64"66+export PREFIX="/Users/macuser/bitcoin/deps"67+make && make install68+# build i386 (32 bit intel) binary69+cd miniupnpc-1.5-i38670+export CFLAGS="-arch i386"71+export LDFLAGS="-arch i386"72+export PREFIX="/Users/macuser/bitcoin/deps"73+make74+75+# combine the libs76+cd ~/bitcoin/deps77+lipo -arch i386 miniupnpc-1.5-i386/libminiupnpc.a -arch x86_64 miniupnpc-1.5-x86_64/libminiupnpc.a -o lib/libminiupnpc.a -create78+79+Verify your binaries80+81+file lib/libminiupnpc.a82+83+output should look like this:84+85+lib/libminiupnpc.a: Mach-O universal binary with 2 architectures86+lib/libminiupnpc.a (for architecture i386):	current ar archive random library87+lib/libminiupnpc.a (for architecture x86_64):	current ar archive random library88 89 90 Berkeley DB

build-unix.txt (modified)

1--- v0.3.20/build-unix.txt2+++ v0.3.21/build-unix.txt3@@ -3,7 +3,8 @@4 file license.txt or http://www.opensource.org/licenses/mit-license.php.5 This product includes software developed by the OpenSSL Project for use in6 the OpenSSL Toolkit (http://www.openssl.org/).  This product includes7-cryptographic software written by Eric Young (eay@cryptsoft.com).8+cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP9+software written by Thomas Bernard.10 11 12 UNIX BUILD NOTES13@@ -29,17 +30,22 @@14 15 If using Boost 1.37, append -mt to the boost libraries in the makefile.16 17-We're using wxWidgets 2.9.0, which uses UTF-8.  Don't try 2.8, it won't work.18-The build hasn't been updated to work with wxWidgets 2.9.1 yet.19+Requires wxWidgets 2.9.0 or greater, which uses UTF-8.  Don't try 2.8, it20+won't work.21 22 You need to download wxWidgets from http://www.wxwidgets.org/downloads/23 and build it yourself.  See the build instructions and configure parameters24 below.25 26+Requires miniupnpc for UPnP port mapping.  To compile with UPnP support,27+install miniupnpc and compile after setting USE_UPNP.  It can be downloaded28+from http://miniupnp.tuxfamily.org/files/.  29+30 Licenses of statically linked libraries:31 wxWidgets      LGPL 2.1 with very liberal exceptions32 Berkeley DB    New BSD license with additional requirement that linked software must be free open source33 Boost          MIT-like license34+miniupnpc      New (3-clause) BSD license35 36 Versions used in this release:37 GCC          4.3.338@@ -47,6 +53,7 @@39 wxWidgets    2.9.040 Berkeley DB  4.7.25.NC41 Boost        1.3742+miniupnpc    1.543 44 45 Notes46@@ -73,6 +80,15 @@47 ldconfig48 49 50+miniupnpc51+---------52+tar -xzvf miniupnpc-1.5.tar.gz53+cd miniupnpc-1.554+make55+sudo su56+make install57+58+59 Berkeley DB60 -----------61 You need Berkeley DB 4.7.  Don't use 4.8, the database/log0000* files

db.cpp (modified)

1--- v0.3.20/db.cpp2+++ v0.3.21/db.cpp3@@ -668,8 +668,8 @@4 #endif5 6     //// todo: shouldn't we catch exceptions and try to recover and continue?7+    CRITICAL_BLOCK(cs_mapWallet)8     CRITICAL_BLOCK(cs_mapKeys)9-    CRITICAL_BLOCK(cs_mapWallet)10     {11         // Get cursor12         Dbc* pcursor = GetCursor();13@@ -790,7 +790,7 @@14                 if (strKey == "fMinimizeOnClose")   ssValue >> fMinimizeOnClose;15                 if (strKey == "fUseProxy")          ssValue >> fUseProxy;16                 if (strKey == "addrProxy")          ssValue >> addrProxy;17-18+                if (fHaveUPnP && strKey == "fUseUPnP")           ssValue >> fUseUPnP;19             }20         }21         pcursor->close();22@@ -807,6 +807,8 @@23     printf("fMinimizeOnClose = %d\n", fMinimizeOnClose);24     printf("fUseProxy = %d\n", fUseProxy);25     printf("addrProxy = %s\n", addrProxy.ToString().c_str());26+    if (fHaveUPnP)27+        printf("fUseUPnP = %d\n", fUseUPnP);28 29 30     // Upgrade31@@ -843,7 +845,7 @@32         keyUser.MakeNewKey();33         if (!AddKey(keyUser))34             return false;35-        if (!SetAddressBookName(PubKeyToAddress(keyUser.GetPubKey()), "Your Address"))36+        if (!SetAddressBookName(PubKeyToAddress(keyUser.GetPubKey()), ""))37             return false;38         CWalletDB().WriteDefaultKey(keyUser.GetPubKey());39     }

db.h (modified)

1--- v0.3.20/db.h2+++ v0.3.21/db.h3@@ -13,6 +13,7 @@4 class CWalletTx;5 class CAccount;6 class CAccountingEntry;7+class CBlockLocator;8 9 extern map<string, string> mapAddressBook;10 extern CCriticalSection cs_mapAddressBook;11@@ -405,6 +406,17 @@12         return Write(make_pair(string("key"), vchPubKey), vchPrivKey, false);13     }14 15+    bool WriteBestBlock(const CBlockLocator& locator)16+    {17+        nWalletDBUpdated++;18+        return Write(string("bestblock"), locator);19+    }20+21+    bool ReadBestBlock(CBlockLocator& locator)22+    {23+        return Read(string("bestblock"), locator);24+    }25+26     bool ReadDefaultKey(vector<unsigned char>& vchPubKey)27     {28         vchPubKey.clear();

init.cpp (modified)

1--- v0.3.20/init.cpp2+++ v0.3.21/init.cpp3@@ -41,6 +41,7 @@4         DBFlush(false);5         StopNode();6         DBFlush(true);7+        boost::filesystem::remove(GetPidFile());8         CreateThread(ExitTimeout, NULL);9         Sleep(50);10         printf("Bitcoin exiting\n\n");11@@ -74,32 +75,13 @@12 #ifndef GUI13 int main(int argc, char* argv[])14 {15-    for (int i = 1; i < argc; i++)16-        if (!IsSwitchChar(argv[i][0]))17-            fCommandLine = true;18-    fDaemon = !fCommandLine;19-20-#ifdef __WXGTK__21-    if (!fCommandLine)22-    {23-        // Daemonize24-        pid_t pid = fork();25-        if (pid < 0)26-        {27-            fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);28-            return 1;29-        }30-        if (pid > 0)31-            pthread_exit((void*)0);32-    }33-#endif34-35-    if (!AppInit(argc, argv))36-        return 1;37-38-    while (!fShutdown)39-        Sleep(1000000);40-    return 0;41+    bool fRet = false;42+    fRet = AppInit(argc, argv);43+44+    if (fRet && fDaemon)45+        return 0;46+47+    return 1;48 }49 #endif50 51@@ -141,6 +123,8 @@52     sigemptyset(&sa.sa_mask);53     sa.sa_flags = 0;54     sigaction(SIGTERM, &sa, NULL);55+    sigaction(SIGINT, &sa, NULL);56+    sigaction(SIGHUP, &sa, NULL);57 #endif58 59     //60@@ -160,7 +144,7 @@61     {62         string beta = VERSION_IS_BETA ? _(" beta") : "";63         string strUsage = string() +64-          _("Bitcoin version") + " " + FormatVersion(VERSION) + pszSubVer + beta + "\n\n" +65+          _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +66           _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +67             "  bitcoin [options]                   \t  " + "\n" +68             "  bitcoin [options] <command> [params]\t  " + _("Send command to -server or bitcoind\n") +69@@ -168,6 +152,7 @@70             "  bitcoin [options] help <command>    \t\t  " + _("Get help for a command\n") +71           _("Options:\n") +72             "  -conf=<file>     \t\t  " + _("Specify configuration file (default: bitcoin.conf)\n") +73+            "  -pid=<file>      \t\t  " + _("Specify pid file (default: bitcoind.pid)\n") +74             "  -gen             \t\t  " + _("Generate coins\n") +75             "  -gen=0           \t\t  " + _("Don't generate coins\n") +76             "  -min             \t\t  " + _("Start minimized\n") +77@@ -175,10 +160,21 @@78             "  -proxy=<ip:port> \t  "   + _("Connect through socks4 proxy\n") +79             "  -addnode=<ip>    \t  "   + _("Add a node to connect to\n") +80             "  -connect=<ip>    \t\t  " + _("Connect only to the specified node\n") +81-            "  -nolisten        \t  "   + _("Don't accept connections from outside") +82+            "  -nolisten        \t  "   + _("Don't accept connections from outside\n") +83+#ifdef USE_UPNP84+#if USE_UPNP85+            "  -noupnp          \t  "   + _("Don't attempt to use UPnP to map the listening port\n") +86+#else87+            "  -upnp            \t  "   + _("Attempt to use UPnP to map the listening port\n") +88+#endif89+#endif90             "  -paytxfee=<amt>  \t  "   + _("Fee per KB to add to transactions you send\n") +91+#ifdef GUI92             "  -server          \t\t  " + _("Accept command line and JSON-RPC commands\n") +93+#endif94+#ifndef __WXMSW__95             "  -daemon          \t\t  " + _("Run in the background as a daemon and accept commands\n") +96+#endif97             "  -testnet         \t\t  " + _("Use the test network\n") +98             "  -rpcuser=<user>  \t  "   + _("Username for JSON-RPC connections\n") +99             "  -rpcpassword=<pw>\t  "   + _("Password for JSON-RPC connections\n") +100@@ -213,23 +209,65 @@101 102     fDebug = GetBoolArg("-debug");103 104+#ifndef __WXMSW__105+    fDaemon = GetBoolArg("-daemon");106+#else107+    fDaemon = false;108+#endif109+110+    if (fDaemon)111+        fServer = true;112+    else113+        fServer = GetBoolArg("-server");114+115+    /* force fServer when running without GUI */116+#ifndef GUI117+    fServer = true;118+#endif119+120     fPrintToConsole = GetBoolArg("-printtoconsole");121     fPrintToDebugger = GetBoolArg("-printtodebugger");122 123     fTestNet = GetBoolArg("-testnet");124-    125     fNoListen = GetBoolArg("-nolisten");126+    fLogTimestamps = GetBoolArg("-logtimestamps");127+128+    for (int i = 1; i < argc; i++)129+        if (!IsSwitchChar(argv[i][0]))130+            fCommandLine = true;131 132     if (fCommandLine)133     {134         int ret = CommandLineRPC(argc, argv);135         exit(ret);136     }137+138+#ifndef __WXMSW__139+    if (fDaemon)140+    {141+        // Daemonize142+        pid_t pid = fork();143+        if (pid < 0)144+        {145+            fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);146+            return false;147+        }148+        if (pid > 0)149+        {150+            CreatePidFile(GetPidFile(), pid);151+            return true;152+        }153+154+        pid_t sid = setsid();155+        if (sid < 0)156+            fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);157+    }158+#endif159 160     if (!fDebug && !pszSetDataDir[0])161         ShrinkDebugFile();162     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");163-    printf("Bitcoin version %s%s%s\n", FormatVersion(VERSION).c_str(), pszSubVer, VERSION_IS_BETA ? _(" beta") : "");164+    printf("Bitcoin version %s\n", FormatFullVersion().c_str());165 #ifdef GUI166     printf("OS version %s\n", ((string)wxGetOsDescription()).c_str());167     printf("System default language is %d %s\n", g_locale.GetSystemLanguage(), ((string)g_locale.GetSysName()).c_str());168@@ -334,10 +372,21 @@169         strErrors += _("Error loading wallet.dat      \n");170     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);171 172+    CBlockIndex *pindexRescan = pindexBest;173     if (GetBoolArg("-rescan"))174-    {175+        pindexRescan = pindexGenesisBlock;176+    else177+    {178+        CWalletDB walletdb;179+        CBlockLocator locator;180+        if (walletdb.ReadBestBlock(locator))181+            pindexRescan = locator.GetBlockIndex();182+    }183+    if (pindexBest != pindexRescan)184+    {185+        printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);186         nStart = GetTimeMillis();187-        ScanForWalletTransactions(pindexGenesisBlock);188+        ScanForWalletTransactions(pindexRescan);189         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);190     }191 192@@ -416,6 +465,9 @@193         }194     }195 196+    if (mapArgs.count("-dnsseed"))197+        DNSAddressSeed();198+199     if (mapArgs.count("-paytxfee"))200     {201         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))202@@ -425,6 +477,17 @@203         }204         if (nTransactionFee > 0.25 * COIN)205             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);206+    }207+208+    if (fHaveUPnP)209+    {210+#if USE_UPNP211+    if (GetBoolArg("-noupnp"))212+        fUseUPnP = false;213+#else214+    if (GetBoolArg("-upnp"))215+        fUseUPnP = true;216+#endif217     }218 219     //220@@ -443,7 +506,7 @@221     if (!CreateThread(StartNode, NULL))222         wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");223 224-    if (GetBoolArg("-server") || fDaemon)225+    if (fServer)226         CreateThread(ThreadRPCServer, NULL);227 228 #if defined(__WXMSW__) && defined(GUI)229@@ -451,6 +514,11 @@230         SetStartOnSystemStartup(true);231 #endif232 233+#ifndef GUI234+    while (1)235+        Sleep(5000);236+#endif237+238     return true;239 }240 

license.txt (modified)

1--- v0.3.20/license.txt2+++ v0.3.21/license.txt3@@ -1,4 +1,4 @@4-Copyright (c) 2009-2010 Bitcoin Developers5+Copyright (c) 2009-2011 Bitcoin Developers6 7 Permission is hereby granted, free of charge, to any person obtaining a copy8 of this software and associated documentation files (the "Software"), to deal

main.cpp (modified)

1--- v0.3.20/main.cpp2+++ v0.3.21/main.cpp3@@ -65,6 +65,14 @@4 int nLimitProcessors = 1;5 int fMinimizeToTray = true;6 int fMinimizeOnClose = true;7+#ifdef USE_UPNP8+#if USE_UPNP9+int fUseUPnP = true;10+#else11+int fUseUPnP = false;12+#endif13+#endif14+15 16 17 18@@ -136,11 +144,7 @@19                 wtx.fFromMe = wtxIn.fFromMe;20                 fUpdated = true;21             }22-            if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)23-            {24-                wtx.fSpent = wtxIn.fSpent;25-                fUpdated = true;26-            }27+            fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);28         }29 30         //// debug print31@@ -174,9 +178,12 @@32     return true;33 }34 35-bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)36-{37-    if (tx.IsMine() || mapWallet.count(tx.GetHash()))38+bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false)39+{40+    uint256 hash = tx.GetHash();41+    bool fExisted = mapWallet.count(hash);42+    if (fExisted && !fUpdate) return false;43+    if (fExisted || tx.IsMine() || tx.IsFromMe())44     {45         CWalletTx wtx(tx);46         // Get merkle branch if transaction was found in a block47@@ -184,20 +191,7 @@48             wtx.SetMerkleBranch(pblock);49         return AddToWallet(wtx);50     }51-    return true;52-}53-54-bool AddToWalletIfFromMe(const CTransaction& tx, const CBlock* pblock)55-{56-    if (tx.IsFromMe() || mapWallet.count(tx.GetHash()))57-    {58-        CWalletTx wtx(tx);59-        // Get merkle branch if transaction was found in a block60-        if (pblock)61-            wtx.SetMerkleBranch(pblock);62-        return AddToWallet(wtx);63-    }64-    return true;65+    return false;66 }67 68 bool EraseFromWallet(uint256 hash)69@@ -221,10 +215,10 @@70         if (mi != mapWallet.end())71         {72             CWalletTx& wtx = (*mi).second;73-            if (!wtx.fSpent && wtx.vout[prevout.n].IsMine())74+            if (!wtx.IsSpent(prevout.n) && wtx.vout[prevout.n].IsMine())75             {76                 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());77-                wtx.fSpent = true;78+                wtx.MarkSpent(prevout.n);79                 wtx.WriteToDisk();80                 vWalletUpdated.push_back(prevout.hash);81             }82@@ -287,7 +281,7 @@83 84 //////////////////////////////////////////////////////////////////////////////85 //86-// CTransaction87+// CTransaction and CTxIndex88 //89 90 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)91@@ -407,18 +401,20 @@92     return nRequests;93 }94 95-void CWalletTx::GetAmounts(int64& nGenerated, list<pair<string, int64> >& listReceived,96+void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string, int64> >& listReceived,97                            list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const98 {99-    nGenerated = nFee = 0;100+    nGeneratedImmature = nGeneratedMature = nFee = 0;101     listReceived.clear();102     listSent.clear();103     strSentAccount = strFromAccount;104 105     if (IsCoinBase())106     {107-        if (GetDepthInMainChain() >= COINBASE_MATURITY)108-            nGenerated = GetCredit();109+        if (GetBlocksToMaturity() > 0)110+            nGeneratedImmature = CTransaction::GetCredit();111+        else112+            nGeneratedMature = GetCredit();113         return;114     }115 116@@ -466,15 +462,15 @@117 {118     nGenerated = nReceived = nSent = nFee = 0;119 120-    int64 allGenerated, allFee;121-    allGenerated = allFee = 0;122+    int64 allGeneratedImmature, allGeneratedMature, allFee;123+    allGeneratedImmature = allGeneratedMature = allFee = 0;124     string strSentAccount;125     list<pair<string, int64> > listReceived;126     list<pair<string, int64> > listSent;127-    GetAmounts(allGenerated, listReceived, listSent, allFee, strSentAccount);128+    GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);129 130     if (strAccount == "")131-        nGenerated = allGenerated;132+        nGenerated = allGeneratedMature;133     if (strAccount == strSentAccount)134     {135         foreach(const PAIRTYPE(string,int64)& s, listSent)136@@ -678,7 +674,11 @@137 138     // Safety limits139     unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);140-    if (GetSigOpCount() > 2 || nSize < 100)141+    // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service142+    // attacks disallow transactions with more than one SigOp per 34 bytes.143+    // 34 bytes because a TxOut is:144+    //   20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length145+    if (GetSigOpCount() > nSize / 34 || nSize < 100)146         return error("AcceptToMemoryPool() : nonstandard transaction");147 148     // Rather not work on nonstandard transactions149@@ -738,19 +738,29 @@150         if (nFees < GetMinFee(1000))151             return error("AcceptToMemoryPool() : not enough fees");152 153-        // Limit free transactions per 10 minutes154-        if (nFees < CENT && GetBoolArg("-limitfreerelay"))155-        {156-            static int64 nNextReset;157-            static int64 nFreeCount;158-            if (GetTime() > nNextReset)159-            {160-                nNextReset = GetTime() + 10 * 60;161-                nFreeCount = 0;162-            }163-            if (nFreeCount > 150000 && !IsFromMe())164-                return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");165-            nFreeCount += nSize;166+        // Continuously rate-limit free transactions167+        // This mitigates 'penny-flooding' -- sending thousands of free transactions just to168+        // be annoying or make other's transactions take longer to confirm.169+        if (nFees < CENT)170+        {171+            static CCriticalSection cs;172+            static double dFreeCount;173+            static int64 nLastTime;174+            int64 nNow = GetTime();175+176+            CRITICAL_BLOCK(cs)177+            {178+                // Use an exponentially decaying ~10-minute window:179+                dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));180+                nLastTime = nNow;181+                // -limitfreerelay unit is thousand-bytes-per-minute182+                // At default rate it would take over a month to fill 1GB183+                if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe())184+                    return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");185+                if (fDebug)186+                    printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);187+                dFreeCount += nSize;188+            }189         }190     }191 192@@ -891,22 +901,8 @@193             block.ReadFromDisk(pindex, true);194             foreach(CTransaction& tx, block.vtx)195             {196-                uint256 hash = tx.GetHash();197-                if (mapWallet.count(hash)) continue;198-                AddToWalletIfMine(tx, &block);199-                if (mapWallet.count(hash))200-                {201-                    ++ret;202-                    printf("Added missing RECEIVE %s\n", hash.ToString().c_str());203-                    continue;204-                }205-                AddToWalletIfFromMe(tx, &block);206-                if (mapWallet.count(hash))207-                {208-                    ++ret;209-                    printf("Added missing SEND %s\n", hash.ToString().c_str());210-                    continue;211-                }212+                if (AddToWalletIfInvolvingMe(tx, &block))213+                    ret++;214             }215             pindex = pindex->pnext;216         }217@@ -925,33 +921,35 @@218         foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)219         {220             CWalletTx& wtx = item.second;221-            if (wtx.fSpent && wtx.IsCoinBase())222+            if (wtx.IsCoinBase() && wtx.IsSpent(0))223                 continue;224 225             CTxIndex txindex;226+            bool fUpdated = false;227             if (txdb.ReadTxIndex(wtx.GetHash(), txindex))228             {229                 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat230-                if (!wtx.fSpent)231+                if (txindex.vSpent.size() != wtx.vout.size())232                 {233-                    if (txindex.vSpent.size() != wtx.vout.size())234+                    printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());235+                    continue;236+                }237+                for (int i = 0; i < txindex.vSpent.size(); i++)238+                {239+                    if (wtx.IsSpent(i))240+                        continue;241+                    if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())242                     {243-                        printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());244-                        continue;245+                        wtx.MarkSpent(i);246+                        fUpdated = true;247+                        vMissingTx.push_back(txindex.vSpent[i]);248                     }249-                    for (int i = 0; i < txindex.vSpent.size(); i++)250-                    {251-                        if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())252-                        {253-                            wtx.fSpent = true;254-                            vMissingTx.push_back(txindex.vSpent[i]);255-                        }256-                    }257-                    if (wtx.fSpent)258-                    {259-                        printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());260-                        wtx.WriteToDisk();261-                    }262+                }263+                if (fUpdated)264+                {265+                    printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());266+                    wtx.MarkDirty();267+                    wtx.WriteToDisk();268                 }269             }270             else271@@ -1034,6 +1032,22 @@272     }273 }274 275+int CTxIndex::GetDepthInMainChain() const276+{277+    // Read block header278+    CBlock block;279+    if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))280+        return 0;281+    // Find the block in the index282+    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());283+    if (mi == mapBlockIndex.end())284+        return 0;285+    CBlockIndex* pindex = (*mi).second;286+    if (!pindex || !pindex->IsInMainChain())287+        return 0;288+    return 1 + nBestHeight - pindex->nHeight;289+}290+291 292 293 294@@ -1144,7 +1158,7 @@295 296 bool IsInitialBlockDownload()297 {298-    if (pindexBest == NULL || (!fTestNet && nBestHeight < 105000))299+    if (pindexBest == NULL || (!fTestNet && nBestHeight < 118000))300         return true;301     static int64 nLastUpdate;302     static CBlockIndex* pindexLastBest;303@@ -1433,7 +1447,7 @@304 305     // Watch for transactions paying to me306     foreach(CTransaction& tx, vtx)307-        AddToWalletIfMine(tx, this);308+        AddToWalletIfInvolvingMe(tx, this, true);309 310     return true;311 }312@@ -1571,6 +1585,15 @@313             InvalidChainFound(pindexNew);314             return error("SetBestChain() : Reorganize failed");315         }316+    }317+318+    // Update best block in wallet (so we can detect restored wallets)319+    if (!IsInitialBlockDownload())320+    {321+        CWalletDB walletdb;322+        const CBlockLocator locator(pindexNew);323+        if (!walletdb.WriteBestBlock(locator))324+            return error("SetBestChain() : WriteWalletBest failed");325     }326 327     // New best block328@@ -1710,7 +1733,8 @@329             (nHeight ==  68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||330             (nHeight ==  70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||331             (nHeight ==  74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) ||332-            (nHeight == 105000 && hash != uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")))333+            (nHeight == 105000 && hash != uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) ||334+            (nHeight == 118000 && hash != uint256("0x000000000000774a7f8a7a12dc906ddb9e17e75d684f15e00f8767f9e8f36553")))335             return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);336 337     // Write block to history file338@@ -1727,7 +1751,7 @@339     if (hashBestChain == hash)340         CRITICAL_BLOCK(cs_vNodes)341             foreach(CNode* pnode, vNodes)342-                if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 105000))343+                if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 118000))344                     pnode->PushInventory(CInv(MSG_BLOCK, hash));345 346     return true;347@@ -2365,6 +2389,10 @@348             pfrom->fDisconnect = true;349             return true;350         }351+352+        // Be shy and don't send version until we hear353+        if (pfrom->fInbound)354+            pfrom->PushVersion();355 356         pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);357 358@@ -2662,7 +2690,7 @@359         bool fMissingInputs = false;360         if (tx.AcceptToMemoryPool(true, &fMissingInputs))361         {362-            AddToWalletIfMine(tx, NULL);363+            AddToWalletIfInvolvingMe(tx, NULL, true);364             RelayMessage(inv, vMsg);365             mapAlreadyAskedFor.erase(inv);366             vWorkQueue.push_back(inv.hash);367@@ -2683,7 +2711,7 @@368                     if (tx.AcceptToMemoryPool(true))369                     {370                         printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());371-                        AddToWalletIfMine(tx, NULL);372+                        AddToWalletIfInvolvingMe(tx, NULL, true);373                         RelayMessage(inv, vMsg);374                         mapAlreadyAskedFor.erase(inv);375                         vWorkQueue.push_back(inv.hash);376@@ -3327,18 +3355,7 @@377                 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;378 379                 // Read block header380-                int nConf = 0;381-                CBlock block;382-                if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))383-                {384-                    map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(block.GetHash());385-                    if (it != mapBlockIndex.end())386-                    {387-                        CBlockIndex* pindex = (*it).second;388-                        if (pindex->IsInMainChain())389-                            nConf = 1 + nBestHeight - pindex->nHeight;390-                    }391-                }392+                int nConf = txindex.GetDepthInMainChain();393 394                 dPriority += (double)nValueIn * nConf;395 396@@ -3383,7 +3400,7 @@397                 continue;398 399             // Transaction fee required depends on block size400-            bool fAllowFree = (nBlockSize + nTxSize < 4000 || dPriority > COIN * 144 / 250);401+            bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));402             int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);403 404             // Connecting shouldn't fail due to dependency on other memory pool transactions405@@ -3709,9 +3726,9 @@406         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)407         {408             CWalletTx* pcoin = &(*it).second;409-            if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())410+            if (!pcoin->IsFinal() || !pcoin->IsConfirmed())411                 continue;412-            nTotal += pcoin->GetCredit();413+            nTotal += pcoin->GetAvailableCredit();414         }415     }416 417@@ -3720,14 +3737,16 @@418 }419 420 421-bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<CWalletTx*>& setCoinsRet)422+bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet)423 {424     setCoinsRet.clear();425+    nValueRet = 0;426 427     // List of values less than target428-    int64 nLowestLarger = INT64_MAX;429-    CWalletTx* pcoinLowestLarger = NULL;430-    vector<pair<int64, CWalletTx*> > vValue;431+    pair<int64, pair<CWalletTx*,unsigned int> > coinLowestLarger;432+    coinLowestLarger.first = INT64_MAX;433+    coinLowestLarger.second.first = NULL;434+    vector<pair<int64, pair<CWalletTx*,unsigned int> > > vValue;435     int64 nTotalLower = 0;436 437     CRITICAL_BLOCK(cs_mapWallet)438@@ -3740,41 +3759,68 @@439 440        foreach(CWalletTx* pcoin, vCoins)441        {442-            if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())443+            if (!pcoin->IsFinal() || !pcoin->IsConfirmed())444+                continue;445+446+            if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)447                 continue;448 449             int nDepth = pcoin->GetDepthInMainChain();450             if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))451                 continue;452 453-            int64 n = pcoin->GetCredit();454-            if (n <= 0)455-                continue;456-            if (n < nTargetValue)457-            {458-                vValue.push_back(make_pair(n, pcoin));459-                nTotalLower += n;460-            }461-            else if (n == nTargetValue)462-            {463-                setCoinsRet.insert(pcoin);464-                return true;465-            }466-            else if (n < nLowestLarger)467-            {468-                nLowestLarger = n;469-                pcoinLowestLarger = pcoin;470-            }471-        }472-    }473-474-    if (nTotalLower < nTargetValue)475-    {476-        if (pcoinLowestLarger == NULL)477+            for (int i = 0; i < pcoin->vout.size(); i++)478+            {479+                if (pcoin->IsSpent(i) || !pcoin->vout[i].IsMine())480+                    continue;481+482+                int64 n = pcoin->vout[i].nValue;483+484+                if (n <= 0)485+                    continue;486+487+                pair<int64,pair<CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));488+489+                if (n == nTargetValue)490+                {491+                    setCoinsRet.insert(coin.second);492+                    nValueRet += coin.first;493+                    return true;494+                }495+                else if (n < nTargetValue + CENT)496+                {497+                    vValue.push_back(coin);498+                    nTotalLower += n;499+                }500+                else if (n < coinLowestLarger.first)501+                {502+                    coinLowestLarger = coin;503+                }504+            }505+        }506+    }507+508+    if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)509+    {510+        for (int i = 0; i < vValue.size(); ++i)511+        {512+            setCoinsRet.insert(vValue[i].second);513+            nValueRet += vValue[i].first;514+        }515+        return true;516+    }517+518+    if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))519+    {520+        if (coinLowestLarger.second.first == NULL)521             return false;522-        setCoinsRet.insert(pcoinLowestLarger);523+        setCoinsRet.insert(coinLowestLarger.second);524+        nValueRet += coinLowestLarger.first;525         return true;526     }527+528+    if (nTotalLower >= nTargetValue + CENT)529+        nTargetValue += CENT;530 531     // Solve subset sum by stochastic approximation532     sort(vValue.rbegin(), vValue.rend());533@@ -3812,13 +3858,18 @@534     }535 536     // If the next larger is still closer, return it537-    if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)538-        setCoinsRet.insert(pcoinLowestLarger);539-    else540-    {541+    if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)542+    {543+        setCoinsRet.insert(coinLowestLarger.second);544+        nValueRet += coinLowestLarger.first;545+    }546+    else {547         for (int i = 0; i < vValue.size(); i++)548             if (vfBest[i])549+            {550                 setCoinsRet.insert(vValue[i].second);551+                nValueRet += vValue[i].first;552+            }553 554         //// debug print555         printf("SelectCoins() best subset: ");556@@ -3831,18 +3882,28 @@557     return true;558 }559 560-bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)561-{562-    return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet) ||563-            SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet) ||564-            SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet));565-}566-567-568-569-570-bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)571-{572+bool SelectCoins(int64 nTargetValue, set<pair<CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet)573+{574+    return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||575+            SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||576+            SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));577+}578+579+580+581+582+bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)583+{584+    int64 nValue = 0;585+    foreach (const PAIRTYPE(CScript, int64)& s, vecSend)586+    {587+        if (nValue < 0)588+            return false;589+        nValue += s.second;590+    }591+    if (vecSend.empty() || nValue < 0)592+        return false;593+594     CRITICAL_BLOCK(cs_main)595     {596         // txdb must be opened before the mapWallet lock597@@ -3855,23 +3916,23 @@598                 wtxNew.vin.clear();599                 wtxNew.vout.clear();600                 wtxNew.fFromMe = true;601-                if (nValue < 0)602+603+                int64 nTotalValue = nValue + nFeeRet;604+                double dPriority = 0;605+                // vouts to the payees606+                foreach (const PAIRTYPE(CScript, int64)& s, vecSend)607+                    wtxNew.vout.push_back(CTxOut(s.second, s.first));608+609+                // Choose coins to use610+                set<pair<CWalletTx*,unsigned int> > setCoins;611+                int64 nValueIn = 0;612+                if (!SelectCoins(nTotalValue, setCoins, nValueIn))613                     return false;614-                int64 nValueOut = nValue;615-                int64 nTotalValue = nValue + nFeeRet;616-617-                // Choose coins to use618-                set<CWalletTx*> setCoins;619-                if (!SelectCoins(nTotalValue, setCoins))620-                    return false;621-                int64 nValueIn = 0;622-                foreach(CWalletTx* pcoin, setCoins)623-                    nValueIn += pcoin->GetCredit();624-625-                // Fill a vout to the payee626-                bool fChangeFirst = GetRand(2);627-                if (!fChangeFirst)628-                    wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));629+                foreach(PAIRTYPE(CWalletTx*, unsigned int) pcoin, setCoins)630+                {631+                    int64 nCredit = pcoin.first->vout[pcoin.second].nValue;632+                    dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();633+                }634 635                 // Fill a vout back to self with any change636                 int64 nChange = nValueIn - nTotalValue;637@@ -3890,41 +3951,38 @@638 639                     // Fill a vout to ourself, using same address type as the payment640                     CScript scriptChange;641-                    if (scriptPubKey.GetBitcoinAddressHash160() != 0)642+                    if (vecSend[0].first.GetBitcoinAddressHash160() != 0)643                         scriptChange.SetBitcoinAddress(vchPubKey);644                     else645                         scriptChange << vchPubKey << OP_CHECKSIG;646-                    wtxNew.vout.push_back(CTxOut(nChange, scriptChange));647+648+                    // Insert change txn at random position:649+                    vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());650+                    wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));651                 }652                 else653                     reservekey.ReturnKey();654 655-                // Fill a vout to the payee656-                if (fChangeFirst)657-                    wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));658-659                 // Fill vin660-                foreach(CWalletTx* pcoin, setCoins)661-                    for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)662-                        if (pcoin->vout[nOut].IsMine())663-                            wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));664+                foreach(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)665+                    wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));666 667                 // Sign668                 int nIn = 0;669-                foreach(CWalletTx* pcoin, setCoins)670-                    for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)671-                        if (pcoin->vout[nOut].IsMine())672-                            if (!SignSignature(*pcoin, wtxNew, nIn++))673-                                return false;674+                foreach(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)675+                    if (!SignSignature(*coin.first, wtxNew, nIn++))676+                        return false;677 678                 // Limit size679                 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);680                 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)681                     return false;682+                dPriority /= nBytes;683 684                 // Check that enough fee is included685                 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);686-                int64 nMinFee = wtxNew.GetMinFee();687+                bool fAllowFree = CTransaction::AllowFree(dPriority);688+                int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);689                 if (nFeeRet < max(nPayFee, nMinFee))690                 {691                     nFeeRet = max(nPayFee, nMinFee);692@@ -3942,6 +4000,13 @@693     return true;694 }695 696+bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)697+{698+    vector< pair<CScript, int64> > vecSend;699+    vecSend.push_back(make_pair(scriptPubKey, nValue));700+    return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);701+}702+703 // Call after CreateTransaction unless you want to abort704 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)705 {706@@ -3965,12 +4030,11 @@707             // Mark old coins as spent708             set<CWalletTx*> setCoins;709             foreach(const CTxIn& txin, wtxNew.vin)710-                setCoins.insert(&mapWallet[txin.prevout.hash]);711-            foreach(CWalletTx* pcoin, setCoins)712-            {713-                pcoin->fSpent = true;714-                pcoin->WriteToDisk();715-                vWalletUpdated.push_back(pcoin->GetHash());716+            {717+                CWalletTx &pcoin = mapWallet[txin.prevout.hash];718+                pcoin.MarkSpent(txin.prevout.n);719+                pcoin.WriteToDisk();720+                vWalletUpdated.push_back(pcoin.GetHash());721             }722         }723 724@@ -3994,35 +4058,35 @@725 726 727 728+// requires cs_main lock729 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)730 {731-    CRITICAL_BLOCK(cs_main)732-    {733-        CReserveKey reservekey;734-        int64 nFeeRequired;735-        if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))736-        {737-            string strError;738-            if (nValue + nFeeRequired > GetBalance())739-                strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s  "), FormatMoney(nFeeRequired).c_str());740-            else741-                strError = _("Error: Transaction creation failed  ");742-            printf("SendMoney() : %s", strError.c_str());743-            return strError;744-        }745-746-        if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))747-            return "ABORTED";748-749-        if (!CommitTransaction(wtxNew, reservekey))750-            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.");751-    }752+    CReserveKey reservekey;753+    int64 nFeeRequired;754+    if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))755+    {756+        string strError;757+        if (nValue + nFeeRequired > GetBalance())758+            strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds  "), FormatMoney(nFeeRequired).c_str());759+        else760+            strError = _("Error: Transaction creation failed  ");761+        printf("SendMoney() : %s", strError.c_str());762+        return strError;763+    }764+765+    if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))766+        return "ABORTED";767+768+    if (!CommitTransaction(wtxNew, reservekey))769+        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.");770+771     MainFrameRepaint();772     return "";773 }774 775 776 777+// requires cs_main lock778 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)779 {780     // Check amount

main.h (modified)

1--- v0.3.20/main.h2+++ v0.3.21/main.h3@@ -22,6 +22,11 @@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+#ifdef USE_UPNP8+static const int fHaveUPnP = true;9+#else10+static const int fHaveUPnP = false;11+#endif12 13 14 15@@ -55,6 +60,7 @@16 extern int nLimitProcessors;17 extern int fMinimizeToTray;18 extern int fMinimizeOnClose;19+extern int fUseUPnP;20 21 22 23@@ -77,6 +83,7 @@24 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);25 bool SendMessages(CNode* pto, bool fSendTrickle);26 int64 GetBalance();27+bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);28 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);29 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);30 bool BroadcastTransaction(CWalletTx& wtxNew);31@@ -574,6 +581,13 @@32         return nValueOut;33     }34 35+    static bool AllowFree(double dPriority)36+    {37+        // Large (in bytes) low-priority (new, small-coin) transactions38+        // need a fee.39+        return dPriority > COIN * 144 / 250;40+    }41+42     int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true) const43     {44         // Base fee is 1 cent per kilobyte45@@ -730,6 +744,7 @@46         fMerkleVerified = false;47     }48 49+50     IMPLEMENT_SERIALIZE51     (52         nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);53@@ -766,15 +781,17 @@54     unsigned int fTimeReceivedIsTxTime;55     unsigned int nTimeReceived;  // time received by this node56     char fFromMe;57-    char fSpent;58     string strFromAccount;59+    vector<char> vfSpent;60 61     // memory only62     mutable char fDebitCached;63     mutable char fCreditCached;64+    mutable char fAvailableCreditCached;65     mutable char fChangeCached;66     mutable int64 nDebitCached;67     mutable int64 nCreditCached;68+    mutable int64 nAvailableCreditCached;69     mutable int64 nChangeCached;70 71     // memory only UI hints72@@ -806,13 +823,15 @@73         fTimeReceivedIsTxTime = false;74         nTimeReceived = 0;75         fFromMe = false;76-        fSpent = false;77         strFromAccount.clear();78+        vfSpent.clear();79         fDebitCached = false;80         fCreditCached = false;81+        fAvailableCreditCached = false;82         fChangeCached = false;83         nDebitCached = 0;84         nCreditCached = 0;85+        nAvailableCreditCached = 0;86         nChangeCached = 0;87         nTimeDisplayed = 0;88         nLinesDisplayed = 0;89@@ -824,21 +843,95 @@90         CWalletTx* pthis = const_cast<CWalletTx*>(this);91         if (fRead)92             pthis->Init();93-        nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);94+        char fSpent = false;95+96+        if (!fRead)97+        {98+            pthis->mapValue["fromaccount"] = pthis->strFromAccount;99+100+            string str;101+            foreach(char f, vfSpent)102+            {103+                str += (f ? '1' : '0');104+                if (f)105+                    fSpent = true;106+            }107+            pthis->mapValue["spent"] = str;108+        }109+110+        nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);111         READWRITE(vtxPrev);112-113-        pthis->mapValue["fromaccount"] = pthis->strFromAccount;114         READWRITE(mapValue);115-        pthis->strFromAccount = pthis->mapValue["fromaccount"];116-        pthis->mapValue.erase("fromaccount");117-        pthis->mapValue.erase("version");118-119         READWRITE(vOrderForm);120         READWRITE(fTimeReceivedIsTxTime);121         READWRITE(nTimeReceived);122         READWRITE(fFromMe);123         READWRITE(fSpent);124+125+        if (fRead)126+        {127+            pthis->strFromAccount = pthis->mapValue["fromaccount"];128+129+            if (mapValue.count("spent"))130+                foreach(char c, pthis->mapValue["spent"])131+                    pthis->vfSpent.push_back(c != '0');132+            else133+                pthis->vfSpent.assign(vout.size(), fSpent);134+        }135+136+        pthis->mapValue.erase("fromaccount");137+        pthis->mapValue.erase("version");138+        pthis->mapValue.erase("spent");139     )140+141+    // marks certain txout's as spent142+    // returns true if any update took place143+    bool UpdateSpent(const vector<char>& vfNewSpent)144+    {145+        bool fReturn = false;146+        for (int i=0; i < vfNewSpent.size(); i++)147+        {148+            if (i == vfSpent.size())149+                break;150+151+            if (vfNewSpent[i] && !vfSpent[i])152+            {153+                vfSpent[i] = true;154+                fReturn = true;155+                fAvailableCreditCached = false;156+            }157+        }158+        return fReturn;159+    }160+161+    void MarkDirty()162+    {163+        fCreditCached = false;164+        fAvailableCreditCached = false;165+        fDebitCached = false;166+        fChangeCached = false;167+    }168+169+    void MarkSpent(unsigned int nOut)170+    {171+        if (nOut >= vout.size())172+            throw runtime_error("CWalletTx::MarkSpent() : nOut out of range");173+        vfSpent.resize(vout.size());174+        if (!vfSpent[nOut])175+        {176+            vfSpent[nOut] = true;177+            fAvailableCreditCached = false;178+        }179+    }180+181+    bool IsSpent(unsigned int nOut) const182+    {183+        if (nOut >= vout.size())184+            throw runtime_error("CWalletTx::IsSpent() : nOut out of range");185+        if (nOut >= vfSpent.size())186+            return false;187+        return (!!vfSpent[nOut]);188+    }189 190     int64 GetDebit() const191     {192@@ -865,6 +958,33 @@193         return nCreditCached;194     }195 196+    int64 GetAvailableCredit(bool fUseCache=true) const197+    {198+        // Must wait until coinbase is safely deep enough in the chain before valuing it199+        if (IsCoinBase() && GetBlocksToMaturity() > 0)200+            return 0;201+202+        if (fUseCache && fAvailableCreditCached)203+            return nAvailableCreditCached;204+205+        int64 nCredit = 0;206+        for (int i = 0; i < vout.size(); i++)207+        {208+            if (!IsSpent(i))209+            {210+                const CTxOut &txout = vout[i];211+                nCredit += txout.GetCredit();212+                if (!MoneyRange(nCredit))213+                    throw runtime_error("CWalletTx::GetAvailableCredit() : value out of range");214+            }215+        }216+217+        nAvailableCreditCached = nCredit;218+        fAvailableCreditCached = true;219+        return nCredit;220+    }221+222+223     int64 GetChange() const224     {225         if (fChangeCached)226@@ -874,7 +994,7 @@227         return nChangeCached;228     }229 230-    void GetAmounts(int64& nGenerated, list<pair<string /* address */, int64> >& listReceived,231+    void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string /* address */, int64> >& listReceived,232                     list<pair<string /* address */, int64> >& listSent, int64& nFee, string& strSentAccount) const;233 234     void GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived, 235@@ -998,6 +1118,7 @@236     {237         return !(a == b);238     }239+    int GetDepthInMainChain() const;240 };241 242 

makefile.mingw (modified)

1--- v0.3.20/makefile.mingw2+++ v0.3.21/makefile.mingw3@@ -2,6 +2,7 @@4 # Distributed under the MIT/X11 software license, see the accompanying5 # file license.txt or http://www.opensource.org/licenses/mit-license.php.6 7+USE_UPNP:=08 9 INCLUDEPATHS= \10  -I"C:\boost-1.43.0-mgw" \11@@ -25,14 +26,22 @@12  -l boost_program_options-mgw45-mt-s-1_43 \13  -l boost_thread-mgw45-mt-s-1_43 \14  -l db_cxx \15- -l eay32 \16- -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 shlwapi17+ -l eay3218 19 DEFS=-DWIN32 -D__WXMSW__ -D_WINDOWS -DNOPCH20 DEBUGFLAGS=-g -D__WXDEBUG__21 CFLAGS=-mthreads -O2 -w -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(DEFS) $(INCLUDEPATHS)22 HEADERS=headers.h strlcpy.h serialize.h uint256.h util.h key.h bignum.h base58.h \23     script.h db.h net.h irc.h main.h rpc.h uibase.h ui.h noui.h init.h24+25+ifdef USE_UPNP26+ INCLUDEPATHS += -I"C:\upnpc-exe-win32-20110215"27+ LIBPATHS += -L"C:\upnpc-exe-win32-20110215"28+ LIBS += -l miniupnpc -l iphlpapi29+ DEFS += -DSTATICLIB -DUSE_UPNP=$(USE_UPNP)30+endif31+32+LIBS += -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 shlwapi33 34 OBJS= \35     obj/util.o \

makefile.osx (modified)

1--- v0.3.20/makefile.osx2+++ v0.3.21/makefile.osx3@@ -15,6 +15,8 @@4  -L"$(DEPSDIR)/lib"5 6 WXLIBS=$(shell $(DEPSDIR)/bin/wx-config --libs --static)7+8+USE_UPNP:=09 10 LIBS= -dead_strip \11  $(DEPSDIR)/lib/libdb_cxx-4.8.a \12@@ -44,6 +46,11 @@13     obj/init.o \14     cryptopp/obj/sha.o \15     cryptopp/obj/cpu.o16+17+ifdef USE_UPNP18+	LIBS += $(DEPSDIR)/lib/libminiupnpc.a19+	DEFS += -DUSE_UPNP=$(USE_UPNP)20+endif21 	22 23 all: bitcoin

makefile.unix (modified)

1--- v0.3.20/makefile.unix2+++ v0.3.21/makefile.unix3@@ -2,18 +2,15 @@4 # Distributed under the MIT/X11 software license, see the accompanying5 # file license.txt or http://www.opensource.org/licenses/mit-license.php.6 7+CXX=g++8 9-INCLUDEPATHS= \10- -I"/usr/local/include/wx-2.9" \11- -I"/usr/local/lib/wx/include/gtk2-unicode-debug-static-2.9"12+WXINCLUDEPATHS=$(shell wx-config --cxxflags)13 14-# for wxWidgets 2.9.1, add -l Xxf86vm15-WXLIBS= \16- -Wl,-Bstatic \17-   -l wx_gtk2ud-2.9 \18- -Wl,-Bdynamic \19-   -l gtk-x11-2.0 \20-   -l SM21+WXLIBS=$(shell wx-config --libs)22+23+USE_UPNP:=024+25+DEFS=-DNOPCH -DFOURWAYSSE2 -DUSE_SSL26 27 # for boost 1.37, add -mt to the boost libraries28 LIBS= \29@@ -24,15 +21,22 @@30    -l boost_thread \31    -l db_cxx \32    -l ssl \33-   -l crypto \34+   -l crypto35+36+ifdef USE_UPNP37+	LIBS += -l miniupnpc38+	DEFS += -DUSE_UPNP=$(USE_UPNP)39+endif40+41+LIBS+= \42  -Wl,-Bdynamic \43    -l gthread-2.0 \44    -l z \45    -l dl46 47-DEFS=-D__WXGTK__ -DNOPCH -DFOURWAYSSE2 -DUSE_SSL48+49 DEBUGFLAGS=-g -D__WXDEBUG__50-CFLAGS=-O2 -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(DEFS) $(INCLUDEPATHS)51+CXXFLAGS=-O2 -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(DEFS)52 HEADERS=headers.h strlcpy.h serialize.h uint256.h util.h key.h bignum.h base58.h \53     script.h db.h net.h irc.h main.h rpc.h uibase.h ui.h noui.h init.h54 55@@ -53,23 +57,23 @@56 57 58 obj/%.o: %.cpp $(HEADERS)59-	g++ -c $(CFLAGS) -DGUI -o $@ $<60+	$(CXX) -c $(CXXFLAGS) $(WXINCLUDEPATHS) -DGUI -o $@ $<61 62 cryptopp/obj/%.o: cryptopp/%.cpp63-	g++ -c $(CFLAGS) -O3 -o $@ $<64+	$(CXX) -c $(CXXFLAGS) -O3 -o $@ $<65 66 obj/sha256.o: sha256.cpp67-	g++ -c $(CFLAGS) -msse2 -O3 -march=amdfam10 -o $@ $<68+	$(CXX) -c $(CXXFLAGS) -msse2 -O3 -march=amdfam10 -o $@ $<69 70 bitcoin: $(OBJS) obj/ui.o obj/uibase.o obj/sha256.o71-	g++ $(CFLAGS) -o $@ $^ $(WXLIBS) $(LIBS)72+	$(CXX) $(CXXFLAGS) -o $@ $^ $(WXLIBS) $(LIBS)73 74 75 obj/nogui/%.o: %.cpp $(HEADERS)76-	g++ -c $(CFLAGS) -o $@ $<77+	$(CXX) -c $(CXXFLAGS) -o $@ $<78 79 bitcoind: $(OBJS:obj/%=obj/nogui/%) obj/sha256.o80-	g++ $(CFLAGS) -o $@ $^ $(LIBS)81+	$(CXX) $(CXXFLAGS) -o $@ $^ $(LIBS)82 83 84 clean:85@@ -77,4 +81,6 @@86 	-rm -f obj/nogui/*.o87 	-rm -f cryptopp/obj/*.o88 	-rm -f headers.h.gch89+	-rm -f bitcoin90+	-rm -f bitcoind91 

net.cpp (modified)

1--- v0.3.20/net.cpp2+++ v0.3.21/net.cpp3@@ -4,11 +4,21 @@4 5 #include "headers.h"6 7+#ifdef USE_UPNP8+#include <miniupnpc/miniwget.h>9+#include <miniupnpc/miniupnpc.h>10+#include <miniupnpc/upnpcommands.h>11+#include <miniupnpc/upnperrors.h>12+#endif13+14 static const int MAX_OUTBOUND_CONNECTIONS = 8;15 16 void ThreadMessageHandler2(void* parg);17 void ThreadSocketHandler2(void* parg);18 void ThreadOpenConnections2(void* parg);19+#ifdef USE_UPNP20+void ThreadMapPort2(void* parg);21+#endif22 bool OpenNetworkConnection(const CAddress& addrConnect);23 24 25@@ -741,7 +751,7 @@26                     CDataStream& vRecv = pnode->vRecv;27                     unsigned int nPos = vRecv.size();28 29-                    if (nPos > 1000*GetArg("-maxreceivebuffer", 2*1000)) {30+                    if (nPos > 1000*GetArg("-maxreceivebuffer", 10*1000)) {31                         if (!pnode->fDisconnect)32                             printf("socket recv flood control disconnect (%d bytes)\n", vRecv.size());33                         pnode->CloseSocketDisconnect();34@@ -806,7 +816,7 @@35                                 pnode->CloseSocketDisconnect();36                             }37                         }38-                        if (vSend.size() > 1000*GetArg("-maxsendbuffer", 256)) {39+                        if (vSend.size() > 1000*GetArg("-maxsendbuffer", 10*1000)) {40                             if (!pnode->fDisconnect)41                                 printf("socket send flood control disconnect (%d bytes)\n", vSend.size());42                             pnode->CloseSocketDisconnect();43@@ -857,7 +867,140 @@44 45 46 47-48+#ifdef USE_UPNP49+void ThreadMapPort(void* parg)50+{51+    IMPLEMENT_RANDOMIZE_STACK(ThreadMapPort(parg));52+    try53+    {54+        vnThreadsRunning[5]++;55+        ThreadMapPort2(parg);56+        vnThreadsRunning[5]--;57+    }58+    catch (std::exception& e) {59+        vnThreadsRunning[5]--;60+        PrintException(&e, "ThreadMapPort()");61+    } catch (...) {62+        vnThreadsRunning[5]--;63+        PrintException(NULL, "ThreadMapPort()");64+    }65+    printf("ThreadMapPort exiting\n");66+}67+68+void ThreadMapPort2(void* parg)69+{70+    printf("ThreadMapPort started\n");71+72+    char port[6];73+    sprintf(port, "%d", ntohs(GetDefaultPort()));74+75+    const char * rootdescurl = 0;76+    const char * multicastif = 0;77+    const char * minissdpdpath = 0;78+    struct UPNPDev * devlist = 0;79+    char lanaddr[64];80+81+    devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);82+83+    struct UPNPUrls urls;84+    struct IGDdatas data;85+    int r;86+87+    r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));88+    if (r == 1)89+    {90+        char intClient[16];91+        char intPort[6];92+93+#ifndef __WXMSW__94+        r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,95+	                        port, port, lanaddr, 0, "TCP", 0);96+#else97+        r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,98+	                        port, port, lanaddr, 0, "TCP", 0, "0");99+#endif100+        if(r!=UPNPCOMMAND_SUCCESS)101+            printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",102+                port, port, lanaddr, r, strupnperror(r));103+        else104+            printf("UPnP Port Mapping successful.\n");105+        loop {106+            if (fShutdown || !fUseUPnP)107+            {108+                r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port, "TCP", 0);109+                printf("UPNP_DeletePortMapping() returned : %d\n", r);110+                freeUPNPDevlist(devlist); devlist = 0;111+                FreeUPNPUrls(&urls);112+                return;113+            }114+            Sleep(2000);115+        }116+    } else {117+        printf("No valid UPnP IGDs found\n");118+        freeUPNPDevlist(devlist); devlist = 0;119+        if (r != 0)120+            FreeUPNPUrls(&urls);121+        loop {122+            if (fShutdown || !fUseUPnP)123+                return;124+            Sleep(2000);125+        }126+    }127+}128+129+void MapPort(bool fMapPort)130+{131+    if (fUseUPnP != fMapPort)132+    {133+        fUseUPnP = fMapPort;134+        CWalletDB().WriteSetting("fUseUPnP", fUseUPnP);135+    }136+    if (fUseUPnP && vnThreadsRunning[5] < 1)137+    {138+        if (!CreateThread(ThreadMapPort, NULL))139+            printf("Error: ThreadMapPort(ThreadMapPort) failed\n");140+    }141+}142+#endif143+144+145+146+147+148+149+150+151+152+153+static const char *strDNSSeed[] = {154+    "bitseed.xf2.org",155+    "bitseed.bitcoin.org.uk",156+};157+158+void DNSAddressSeed()159+{160+    int found = 0;161+162+    printf("Loading addresses from DNS seeds (could take a while)\n");163+164+    for (int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {165+        struct hostent* phostent = gethostbyname(strDNSSeed[seed_idx]);166+        if (!phostent)167+            continue;168+169+        for (int host = 0; phostent->h_addr_list[host] != NULL; host++) {170+            CAddress addr(*(unsigned int*)phostent->h_addr_list[host],171+                          GetDefaultPort(), NODE_NETWORK);172+            addr.nTime = 0;173+            if (addr.IsValid() && addr.GetByte(3) != 127) {174+                AddAddress(addr);175+                found++;176+            }177+        }178+    }179+180+    printf("%d addresses found from DNS seeds\n", found);181+}182 183 184 185@@ -1382,6 +1525,10 @@186     // Start threads187     //188 189+    // Map ports with UPnP190+    if (fHaveUPnP)191+        MapPort(fUseUPnP);192+193     // Get addresses from IRC and advertise ours194     if (!CreateThread(ThreadIRCSeed, NULL))195         printf("Error: CreateThread(ThreadIRCSeed) failed\n");196@@ -1407,7 +1554,11 @@197     fShutdown = true;198     nTransactionsUpdated++;199     int64 nStart = GetTime();200-    while (vnThreadsRunning[0] > 0 || vnThreadsRunning[2] > 0 || vnThreadsRunning[3] > 0 || vnThreadsRunning[4] > 0)201+    while (vnThreadsRunning[0] > 0 || vnThreadsRunning[2] > 0 || vnThreadsRunning[3] > 0 || vnThreadsRunning[4] > 0202+#ifdef USE_UPNP203+        || vnThreadsRunning[5] > 0204+#endif205+    )206     {207         if (GetTime() - nStart > 20)208             break;209@@ -1418,6 +1569,7 @@210     if (vnThreadsRunning[2] > 0) printf("ThreadMessageHandler still running\n");211     if (vnThreadsRunning[3] > 0) printf("ThreadBitcoinMiner still running\n");212     if (vnThreadsRunning[4] > 0) printf("ThreadRPCServer still running\n");213+    if (fHaveUPnP && vnThreadsRunning[5] > 0) printf("ThreadMapPort still running\n");214     while (vnThreadsRunning[2] > 0 || vnThreadsRunning[4] > 0)215         Sleep(20);216     Sleep(50);

net.h (modified)

1--- v0.3.20/net.h2+++ v0.3.21/net.h3@@ -30,6 +30,8 @@4 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);5 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);6 bool AnySubscribed(unsigned int nChannel);7+void MapPort(bool fMapPort);8+void DNSAddressSeed();9 bool BindListenPort(string& strError=REF(string()));10 void StartNode(void* parg);11 bool StopNode();12@@ -571,14 +573,9 @@13         fGetAddr = false;14         vfSubscribe.assign(256, false);15 16-        // Push a version message17-        /// when NTP implemented, change to just nTime = GetAdjustedTime()18-        int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());19-        CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);20-        CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);21-        RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));22-        PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,23-                    nLocalHostNonce, string(pszSubVer), nBestHeight);24+        // Be shy and don't send version until we hear25+        if (!fInbound)26+            PushVersion();27     }28 29     ~CNode()30@@ -735,6 +732,19 @@31 32 33 34+    void PushVersion()35+    {36+        /// when NTP implemented, change to just nTime = GetAdjustedTime()37+        int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());38+        CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);39+        CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);40+        RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));41+        PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,42+                nLocalHostNonce, string(pszSubVer), nBestHeight);43+    }44+45+46+47 48     void PushMessage(const char* pszCommand)49     {

rpc.cpp (modified)

1--- v0.3.20/rpc.cpp2+++ v0.3.21/rpc.cpp3@@ -65,7 +65,7 @@4     double dAmount = value.get_real();5     if (dAmount <= 0.0 || dAmount > 21000000.0)6         throw JSONRPCError(-3, "Invalid amount");7-    int64 nAmount = roundint64(dAmount * 100.00) * CENT;8+    int64 nAmount = roundint64(dAmount * COIN);9     if (!MoneyRange(nAmount))10         throw JSONRPCError(-3, "Invalid amount");11     return nAmount;12@@ -277,7 +277,7 @@13 14     Object obj;15     obj.push_back(Pair("version",       (int)VERSION));16-    obj.push_back(Pair("balance",       (double)GetBalance() / (double)COIN));17+    obj.push_back(Pair("balance",       ValueFromAmount(GetBalance())));18     obj.push_back(Pair("blocks",        (int)nBestHeight));19     obj.push_back(Pair("connections",   (int)vNodes.size()));20     obj.push_back(Pair("proxy",         (fUseProxy ? addrProxy.ToStringIPPort() : string())));21@@ -287,7 +287,7 @@22     obj.push_back(Pair("hashespersec",  gethashespersec(params, false)));23     obj.push_back(Pair("testnet",       fTestNet));24     obj.push_back(Pair("keypoololdest", (boost::int64_t)GetOldestKeyPoolTime()));25-    obj.push_back(Pair("paytxfee",      (double)nTransactionFee / (double)COIN));26+    obj.push_back(Pair("paytxfee",      ValueFromAmount(nTransactionFee)));27     obj.push_back(Pair("errors",        GetWarnings("statusbar")));28     return obj;29 }30@@ -315,46 +315,45 @@31 }32 33 34+// requires cs_main, cs_mapWallet locks35 string GetAccountAddress(string strAccount, bool bForceNew=false)36 {37     string strAddress;38 39-    CRITICAL_BLOCK(cs_mapWallet)40-    {41-        CWalletDB walletdb;42-        walletdb.TxnBegin();43-44-        CAccount account;45-        walletdb.ReadAccount(strAccount, account);46-47-        // Check if the current key has been used48-        if (!account.vchPubKey.empty())49-        {50-            CScript scriptPubKey;51-            scriptPubKey.SetBitcoinAddress(account.vchPubKey);52-            for (map<uint256, CWalletTx>::iterator it = mapWallet.begin();53-                 it != mapWallet.end() && !account.vchPubKey.empty();54-                 ++it)55-            {56-                const CWalletTx& wtx = (*it).second;57-                foreach(const CTxOut& txout, wtx.vout)58-                    if (txout.scriptPubKey == scriptPubKey)59-                        account.vchPubKey.clear();60-            }61-        }62-63-        // Generate a new key64-        if (account.vchPubKey.empty() || bForceNew)65-        {66-            account.vchPubKey = GetKeyFromKeyPool();67-            string strAddress = PubKeyToAddress(account.vchPubKey);68-            SetAddressBookName(strAddress, strAccount);69-            walletdb.WriteAccount(strAccount, account);70-        }71-72-        walletdb.TxnCommit();73-        strAddress = PubKeyToAddress(account.vchPubKey);74-    }75+    CWalletDB walletdb;76+    walletdb.TxnBegin();77+78+    CAccount account;79+    walletdb.ReadAccount(strAccount, account);80+81+    // Check if the current key has been used82+    if (!account.vchPubKey.empty())83+    {84+        CScript scriptPubKey;85+        scriptPubKey.SetBitcoinAddress(account.vchPubKey);86+        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin();87+             it != mapWallet.end() && !account.vchPubKey.empty();88+             ++it)89+        {90+            const CWalletTx& wtx = (*it).second;91+            foreach(const CTxOut& txout, wtx.vout)92+                if (txout.scriptPubKey == scriptPubKey)93+                    account.vchPubKey.clear();94+        }95+    }96+97+    // Generate a new key98+    if (account.vchPubKey.empty() || bForceNew)99+    {100+        account.vchPubKey = GetKeyFromKeyPool();101+        string strAddress = PubKeyToAddress(account.vchPubKey);102+        SetAddressBookName(strAddress, strAccount);103+        walletdb.WriteAccount(strAccount, account);104+    }105+106+    walletdb.TxnCommit();107+    strAddress = PubKeyToAddress(account.vchPubKey);108+109     return strAddress;110 }111 112@@ -368,7 +367,15 @@113     // Parse the account first so we don't generate a key if there's an error114     string strAccount = AccountFromValue(params[0]);115 116-    return GetAccountAddress(strAccount);117+    Value ret;118+119+    CRITICAL_BLOCK(cs_main)120+    CRITICAL_BLOCK(cs_mapWallet)121+    {122+        ret = GetAccountAddress(strAccount);123+    }124+125+    return ret;126 }127 128 129@@ -381,11 +388,19 @@130             "Sets the account associated with the given address.");131 132     string strAddress = params[0].get_str();133+    uint160 hash160;134+    bool isValid = AddressToHash160(strAddress, hash160);135+    if (!isValid)136+        throw JSONRPCError(-5, "Invalid bitcoin address");137+138+139     string strAccount;140     if (params.size() > 1)141         strAccount = AccountFromValue(params[1]);142 143     // Detect when changing the account of an address that is the 'unused current key' of another account:144+    CRITICAL_BLOCK(cs_main)145+    CRITICAL_BLOCK(cs_mapWallet)146     CRITICAL_BLOCK(cs_mapAddressBook)147     {148         if (mapAddressBook.count(strAddress))149@@ -469,9 +484,13 @@150     if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())151         wtx.mapValue["to"]      = params[3].get_str();152 153-    string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);154-    if (strError != "")155-        throw JSONRPCError(-4, strError);156+    CRITICAL_BLOCK(cs_main)157+    {158+        string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);159+        if (strError != "")160+            throw JSONRPCError(-4, strError);161+    }162+163     return wtx.GetHash().GetHex();164 }165 166@@ -513,7 +532,7 @@167         }168     }169 170-    return (double)nAmount / (double)COIN;171+    return  ValueFromAmount(nAmount);172 }173 174 175@@ -619,46 +638,45 @@176             "If [account] is specified, returns the balance in the account.");177 178     if (params.size() == 0)179-        return ((double)GetBalance() / (double)COIN);180+        return  ValueFromAmount(GetBalance());181+182+    int nMinDepth = 1;183+    if (params.size() > 1)184+        nMinDepth = params[1].get_int();185 186     if (params[0].get_str() == "*") {187         // Calculate total balance a different way from GetBalance()188         // (GetBalance() sums up all unspent TxOuts)189         // getbalance and getbalance '*' should always return the same number.190         int64 nBalance = 0;191-        vector<string> vAccounts;192         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)193         {194             const CWalletTx& wtx = (*it).second;195-            int64 allGenerated, allFee;196-            allGenerated = allFee = 0;197+            if (!wtx.IsFinal())198+                continue;199+200+            int64 allGeneratedImmature, allGeneratedMature, allFee;201+            allGeneratedImmature = allGeneratedMature = allFee = 0;202             string strSentAccount;203             list<pair<string, int64> > listReceived;204             list<pair<string, int64> > listSent;205-            wtx.GetAmounts(allGenerated, listReceived, listSent, allFee, strSentAccount);206-            foreach(const PAIRTYPE(string,int64)& r, listReceived)207-            {208-                nBalance += r.second;209-                if (!count(vAccounts.begin(), vAccounts.end(), r.first))210-                    vAccounts.push_back(r.first);211-            }212+            wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);213+            if (wtx.GetDepthInMainChain() >= nMinDepth)214+                foreach(const PAIRTYPE(string,int64)& r, listReceived)215+                    nBalance += r.second;216             foreach(const PAIRTYPE(string,int64)& r, listSent)217                 nBalance -= r.second;218             nBalance -= allFee;219-            nBalance += allGenerated;220-        }221-        printf("Found %d accounts\n", vAccounts.size());222-        return (double)nBalance / (double)COIN;223+            nBalance += allGeneratedMature;224+        }225+        return  ValueFromAmount(nBalance);226     }227 228     string strAccount = AccountFromValue(params[0]);229-    int nMinDepth = 1;230-    if (params.size() > 1)231-        nMinDepth = params[1].get_int();232 233     int64 nBalance = GetAccountBalance(strAccount, nMinDepth);234 235-    return (double)nBalance / (double)COIN;236+    return ValueFromAmount(nBalance);237 }238 239 240@@ -746,6 +764,7 @@241     if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())242         wtx.mapValue["to"]      = params[5].get_str();243 244+    CRITICAL_BLOCK(cs_main)245     CRITICAL_BLOCK(cs_mapWallet)246     {247         // Check funds248@@ -762,6 +781,70 @@249     return wtx.GetHash().GetHex();250 }251 252+Value sendmany(const Array& params, bool fHelp)253+{254+    if (fHelp || params.size() < 2 || params.size() > 4)255+        throw runtime_error(256+            "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"257+            "amounts are double-precision floating point numbers");258+259+    string strAccount = AccountFromValue(params[0]);260+    Object sendTo = params[1].get_obj();261+    int nMinDepth = 1;262+    if (params.size() > 2)263+        nMinDepth = params[2].get_int();264+265+    CWalletTx wtx;266+    wtx.strFromAccount = strAccount;267+    if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())268+        wtx.mapValue["comment"] = params[3].get_str();269+270+    set<string> setAddress;271+    vector<pair<CScript, int64> > vecSend;272+273+    int64 totalAmount = 0;274+    foreach(const Pair& s, sendTo)275+    {276+        uint160 hash160;277+        string strAddress = s.name_;278+279+        if (setAddress.count(strAddress))280+            throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+strAddress);281+        setAddress.insert(strAddress);282+283+        CScript scriptPubKey;284+        if (!scriptPubKey.SetBitcoinAddress(strAddress))285+            throw JSONRPCError(-5, string("Invalid bitcoin address:")+strAddress);286+        int64 nAmount = AmountFromValue(s.value_); 287+        totalAmount += nAmount;288+289+        vecSend.push_back(make_pair(scriptPubKey, nAmount));290+    }291+292+    CRITICAL_BLOCK(cs_main)293+    CRITICAL_BLOCK(cs_mapWallet)294+    {295+        // Check funds296+        int64 nBalance = GetAccountBalance(strAccount, nMinDepth);297+        if (totalAmount > nBalance)298+            throw JSONRPCError(-6, "Account has insufficient funds");299+300+        // Send301+        CReserveKey keyChange;302+        int64 nFeeRequired = 0;303+        bool fCreated = CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);304+        if (!fCreated)305+        {306+            if (totalAmount + nFeeRequired > GetBalance())307+                throw JSONRPCError(-6, "Insufficient funds");308+            throw JSONRPCError(-4, "Transaction creation failed");309+        }310+        if (!CommitTransaction(wtx, keyChange))311+            throw JSONRPCError(-4, "Transaction commit failed");312+    }313+314+    return wtx.GetHash().GetHex();315+}316 317 318 struct tallyitem319@@ -851,7 +934,7 @@320                 obj.push_back(Pair("address",       strAddress));321                 obj.push_back(Pair("account",       strAccount));322                 obj.push_back(Pair("label",         strAccount)); // deprecated323-                obj.push_back(Pair("amount",        (double)nAmount / (double)COIN));324+                obj.push_back(Pair("amount",        ValueFromAmount(nAmount)));325                 obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));326                 ret.push_back(obj);327             }328@@ -867,7 +950,7 @@329             Object obj;330             obj.push_back(Pair("account",       (*it).first));331             obj.push_back(Pair("label",         (*it).first)); // deprecated332-            obj.push_back(Pair("amount",        (double)nAmount / (double)COIN));333+            obj.push_back(Pair("amount",        ValueFromAmount(nAmount)));334             obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));335             ret.push_back(obj);336         }337@@ -909,21 +992,29 @@338 339 void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)340 {341-    int64 nGenerated, nFee;342+    int64 nGeneratedImmature, nGeneratedMature, nFee;343     string strSentAccount;344     list<pair<string, int64> > listReceived;345     list<pair<string, int64> > listSent;346-    wtx.GetAmounts(nGenerated, listReceived, listSent, nFee, strSentAccount);347+    wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);348 349     bool fAllAccounts = (strAccount == string("*"));350 351     // Generated blocks assigned to account ""352-    if (nGenerated != 0 && (fAllAccounts || strAccount == ""))353+    if ((nGeneratedMature+nGeneratedImmature) != 0 && (fAllAccounts || strAccount == ""))354     {355         Object entry;356         entry.push_back(Pair("account", string("")));357-        entry.push_back(Pair("category", "generate"));358-        entry.push_back(Pair("amount", ValueFromAmount(nGenerated)));359+        if (nGeneratedImmature)360+        {361+            entry.push_back(Pair("category", wtx.GetDepthInMainChain() ? "immature" : "orphan"));362+            entry.push_back(Pair("amount", ValueFromAmount(nGeneratedImmature)));363+        }364+        else365+        {366+            entry.push_back(Pair("category", "generate"));367+            entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature)));368+        }369         if (fLong)370             WalletTxToJSON(wtx, entry);371         ret.push_back(entry);372@@ -1066,23 +1157,26 @@373     CRITICAL_BLOCK(cs_mapWallet)374     CRITICAL_BLOCK(cs_mapAddressBook)375     {376-        foreach(const PAIRTYPE(string, string)& entry, mapAddressBook)377-            mapAccountBalances[entry.second] = 0;378+        foreach(const PAIRTYPE(string, string)& entry, mapAddressBook) {379+            uint160 hash160;380+            if(AddressToHash160(entry.first, hash160) && mapPubKeys.count(hash160)) // This address belongs to me381+                mapAccountBalances[entry.second] = 0;382+        }383 384         for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)385         {386             const CWalletTx& wtx = (*it).second;387-            int64 nGenerated, nFee;388+            int64 nGeneratedImmature, nGeneratedMature, nFee;389             string strSentAccount;390             list<pair<string, int64> > listReceived;391             list<pair<string, int64> > listSent;392-            wtx.GetAmounts(nGenerated, listReceived, listSent, nFee, strSentAccount);393+            wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);394             mapAccountBalances[strSentAccount] -= nFee;395             foreach(const PAIRTYPE(string, int64)& s, listSent)396                 mapAccountBalances[strSentAccount] -= s.second;397             if (wtx.GetDepthInMainChain() >= nMinDepth)398             {399-                mapAccountBalances[""] += nGenerated;400+                mapAccountBalances[""] += nGeneratedMature;401                 foreach(const PAIRTYPE(string, int64)& r, listReceived)402                     if (mapAddressBook.count(r.first))403                         mapAccountBalances[mapAddressBook[r.first]] += r.second;404@@ -1338,6 +1432,7 @@405     make_pair("getbalance",            &getbalance),406     make_pair("move",                  &movecmd),407     make_pair("sendfrom",              &sendfrom),408+    make_pair("sendmany",              &sendmany),409     make_pair("gettransaction",        &gettransaction),410     make_pair("listtransactions",      &listtransactions),411     make_pair("getwork",               &getwork),412@@ -1384,7 +1479,7 @@413 {414     ostringstream s;415     s << "POST / HTTP/1.1\r\n"416-      << "User-Agent: json-rpc/1.0\r\n"417+      << "User-Agent: bitcoin-json-rpc/" << FormatFullVersion() << "\r\n"418       << "Host: 127.0.0.1\r\n"419       << "Content-Type: application/json\r\n"420       << "Content-Length: " << strMsg.size() << "\r\n"421@@ -1398,11 +1493,14 @@422 423 string rfc1123Time()424 {425-    char buffer[32];426+    char buffer[64];427     time_t now;428     time(&now);429     struct tm* now_gmt = gmtime(&now);430-    strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S %Z", now_gmt);431+    string locale(setlocale(LC_TIME, NULL));432+    setlocale(LC_TIME, "C"); // we want posix (aka "C") weekday/month strings433+    strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);434+    setlocale(LC_TIME, locale.c_str());435     return string(buffer);436 }437 438@@ -1411,7 +1509,7 @@439     if (nStatus == 401)440         return strprintf("HTTP/1.0 401 Authorization Required\r\n"441             "Date: %s\r\n"442-            "Server: bitcoin-json-rpc\r\n"443+            "Server: bitcoin-json-rpc/%s\r\n"444             "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"445             "Content-Type: text/html\r\n"446             "Content-Length: 296\r\n"447@@ -1424,7 +1522,7 @@448             "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"449             "</HEAD>\r\n"450             "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"451-            "</HTML>\r\n", rfc1123Time().c_str());452+            "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());453     string strStatus;454          if (nStatus == 200) strStatus = "OK";455     else if (nStatus == 400) strStatus = "Bad Request";456@@ -1436,13 +1534,14 @@457             "Connection: close\r\n"458             "Content-Length: %d\r\n"459             "Content-Type: application/json\r\n"460-            "Server: bitcoin-json-rpc/1.0\r\n"461+            "Server: bitcoin-json-rpc/%s\r\n"462             "\r\n"463             "%s",464         nStatus,465         strStatus.c_str(),466         rfc1123Time().c_str(),467         strMsg.size(),468+        FormatFullVersion().c_str(),469         strMsg.c_str());470 }471 472@@ -1709,6 +1808,8 @@473     asio::io_service io_service;474     ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 8332));475     ip::tcp::acceptor acceptor(io_service, endpoint);476+477+    acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));478 479 #ifdef USE_SSL480     ssl::context context(io_service, ssl::context::sslv23);481@@ -1987,6 +2088,15 @@482         if (strMethod == "sendfrom"               && n > 3) ConvertTo<boost::int64_t>(params[3]);483         if (strMethod == "listtransactions"       && n > 1) ConvertTo<boost::int64_t>(params[1]);484         if (strMethod == "listaccounts"           && n > 0) ConvertTo<boost::int64_t>(params[0]);485+        if (strMethod == "sendmany"               && n > 1)486+        {487+            string s = params[1].get_str();488+            Value v;489+            if (!read_string(s, v) || v.type() != obj_type)490+                throw runtime_error("type mismatch");491+            params[1] = v.get_obj();492+        }493+        if (strMethod == "sendmany"                && n > 2) ConvertTo<boost::int64_t>(params[2]);494 495         // Execute496         Object reply = CallRPC(strMethod, params);

serialize.h (modified)

1--- v0.3.20/serialize.h2+++ v0.3.21/serialize.h3@@ -25,7 +25,7 @@4 class CAutoFile;5 static const unsigned int MAX_SIZE = 0x02000000;6 7-static const int VERSION = 32001;8+static const int VERSION = 32100;9 static const char* pszSubVer = "";10 static const bool VERSION_IS_BETA = true;11 

setup.nsi (modified)

1--- v0.3.20/setup.nsi2+++ v0.3.21/setup.nsi3@@ -4,7 +4,7 @@4 5 # General Symbol Definitions6 !define REGKEY "SOFTWARE\$(^Name)"7-!define VERSION 0.3.208+!define VERSION 0.3.219 !define COMPANY "Bitcoin project"10 !define URL http://www.bitcoin.org/11 12@@ -39,12 +39,12 @@13 !insertmacro MUI_LANGUAGE English14 15 # Installer attributes16-OutFile bitcoin-0.3.20-win32-setup.exe17+OutFile bitcoin-0.3.21-win32-setup.exe18 InstallDir $PROGRAMFILES\Bitcoin19 CRCCheck on20 XPStyle on21 ShowInstDetails show22-VIProductVersion 0.3.20.023+VIProductVersion 0.3.21.024 VIAddVersionKey ProductName Bitcoin25 VIAddVersionKey ProductVersion "${VERSION}"26 VIAddVersionKey CompanyName "${COMPANY}"

ui.cpp (modified)

1--- v0.3.20/ui.cpp2+++ v0.3.21/ui.cpp3@@ -1665,6 +1665,10 @@4     m_checkBoxStartOnSystemStartup->SetValue(fTmpStartOnSystemStartup = GetStartOnSystemStartup());5     m_checkBoxMinimizeToTray->SetValue(fMinimizeToTray);6     m_checkBoxMinimizeOnClose->SetValue(fMinimizeOnClose);7+    if (fHaveUPnP)8+        m_checkBoxUseUPnP->SetValue(fUseUPnP);9+    else10+        m_checkBoxUseUPnP->Enable(false);11     m_checkBoxUseProxy->SetValue(fUseProxy);12     m_textCtrlProxyIP->Enable(fUseProxy);13     m_textCtrlProxyPort->Enable(fUseProxy);14@@ -1784,6 +1788,13 @@15         walletdb.WriteSetting("fMinimizeOnClose", fMinimizeOnClose);16     }17 18+    if (fHaveUPnP && fUseUPnP != m_checkBoxUseUPnP->GetValue())19+    {20+        fUseUPnP = m_checkBoxUseUPnP->GetValue();21+        walletdb.WriteSetting("fUseUPnP", fUseUPnP);22+        MapPort(fUseUPnP);23+    }24+25     fUseProxy = m_checkBoxUseProxy->GetValue();26     walletdb.WriteSetting("fUseProxy", fUseProxy);27 28@@ -1803,7 +1814,7 @@29 30 CAboutDialog::CAboutDialog(wxWindow* parent) : CAboutDialogBase(parent)31 {32-    m_staticTextVersion->SetLabel(strprintf(_("version %s%s BETA"), FormatVersion(VERSION).c_str(), pszSubVer));33+    m_staticTextVersion->SetLabel(strprintf(_("version %s"), FormatFullVersion().c_str()));34 35     // Change (c) into UTF-8 or ANSI copyright symbol36     wxString str = m_staticTextMain->GetLabel();37@@ -1854,7 +1865,7 @@38     if (fontTmp.GetPointSize() > 9);39         fontTmp.SetPointSize(9);40     m_staticTextInstructions->SetFont(fontTmp);41-    SetSize(725, 380);42+    SetSize(725, 180);43 #endif44 45     // Set Icon46@@ -1862,42 +1873,10 @@47     iconSend.CopyFromBitmap(wxBitmap(send16noshadow_xpm));48     SetIcon(iconSend);49 50-    wxCommandEvent event;51-    OnTextAddress(event);52-53     // Fixup the tab order54     m_buttonPaste->MoveAfterInTabOrder(m_buttonCancel);55     m_buttonAddress->MoveAfterInTabOrder(m_buttonPaste);56     this->Layout();57-}58-59-void CSendDialog::OnTextAddress(wxCommandEvent& event)60-{61-    // Check mark62-    event.Skip();63-    bool fBitcoinAddress = IsValidBitcoinAddress(m_textCtrlAddress->GetValue());64-    m_bitmapCheckMark->Show(fBitcoinAddress);65-66-    // Grey out message if bitcoin address67-    bool fEnable = !fBitcoinAddress;68-    m_staticTextFrom->Enable(fEnable);69-    m_textCtrlFrom->Enable(fEnable);70-    m_staticTextMessage->Enable(fEnable);71-    m_textCtrlMessage->Enable(fEnable);72-    m_textCtrlMessage->SetBackgroundColour(wxSystemSettings::GetColour(fEnable ? wxSYS_COLOUR_WINDOW : wxSYS_COLOUR_BTNFACE));73-    if (!fEnable && fEnabledPrev)74-    {75-        strFromSave    = m_textCtrlFrom->GetValue();76-        strMessageSave = m_textCtrlMessage->GetValue();77-        m_textCtrlFrom->SetValue(_("n/a"));78-        m_textCtrlMessage->SetValue(_("Can't include a message when sending to a Bitcoin address"));79-    }80-    else if (fEnable && !fEnabledPrev)81-    {82-        m_textCtrlFrom->SetValue(strFromSave);83-        m_textCtrlMessage->SetValue(strMessageSave);84-    }85-    fEnabledPrev = fEnable;86 }87 88 void CSendDialog::OnKillFocusAmount(wxFocusEvent& event)89@@ -1966,20 +1945,23 @@90 91         if (fBitcoinAddress)92         {93-            // Send to bitcoin address94-            CScript scriptPubKey;95-            scriptPubKey << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;96-97-            string strError = SendMoney(scriptPubKey, nValue, wtx, true);98-            if (strError == "")99-                wxMessageBox(_("Payment sent  "), _("Sending..."));100-            else if (strError == "ABORTED")101-                return; // leave send dialog open102-            else103-            {104-                wxMessageBox(strError + "  ", _("Sending..."));105-                EndModal(false);106-            }107+	    CRITICAL_BLOCK(cs_main)108+	    {109+                // Send to bitcoin address110+                CScript scriptPubKey;111+                scriptPubKey << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;112+113+                string strError = SendMoney(scriptPubKey, nValue, wtx, true);114+                if (strError == "")115+                    wxMessageBox(_("Payment sent  "), _("Sending..."));116+                else if (strError == "ABORTED")117+                    return; // leave send dialog open118+                else119+                {120+                    wxMessageBox(strError + "  ", _("Sending..."));121+                    EndModal(false);122+                }123+	    }124         }125         else126         {127@@ -1993,8 +1975,6 @@128 129             // Message130             wtx.mapValue["to"] = strAddress;131-            wtx.mapValue["from"] = m_textCtrlFrom->GetValue();132-            wtx.mapValue["message"] = m_textCtrlMessage->GetValue();133 134             // Send to IP address135             CSendingDialog* pdialog = new CSendingDialog(this, addr, nValue, wtx);136@@ -2267,7 +2247,7 @@137         if (!CreateTransaction(scriptPubKey, nPrice, wtx, reservekey, nFeeRequired))138         {139             if (nPrice + nFeeRequired > GetBalance())140-                Error(strprintf(_("This is an oversized transaction that requires a transaction fee of %s"), FormatMoney(nFeeRequired).c_str()));141+                Error(strprintf(_("This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds"), FormatMoney(nFeeRequired).c_str()));142             else143                 Error(_("Transaction creation failed"));144             return;145@@ -2839,6 +2819,10 @@146             }147             if (pid > 0)148                 pthread_exit((void*)0);149+150+            pid_t sid = setsid();151+            if (sid < 0)152+                fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);153         }154 155         return true;

ui.h (modified)

1--- v0.3.20/ui.h2+++ v0.3.21/ui.h3@@ -166,7 +166,6 @@4 protected:5     // Event handlers6     void OnKeyDown(wxKeyEvent& event) { HandleCtrlA(event); }7-    void OnTextAddress(wxCommandEvent& event);8     void OnKillFocusAmount(wxFocusEvent& event);9     void OnButtonAddressBook(wxCommandEvent& event);10     void OnButtonPaste(wxCommandEvent& event);

uibase.cpp (modified)

1--- v0.3.20/uibase.cpp2+++ v0.3.21/uibase.cpp3@@ -1,5 +1,5 @@4 ///////////////////////////////////////////////////////////////////////////5-// C++ code generated with wxFormBuilder (version Apr 16 2008)6+// C++ code generated with wxFormBuilder (version Dec 21 2009)7 // http://www.wxformbuilder.org/8 //9 // PLEASE DO "NOT" EDIT THIS FILE!10@@ -61,7 +61,6 @@11 	m_toolBar->Realize();12 	13 	m_statusBar = this->CreateStatusBar( 1, wxST_SIZEGRIP, wxID_ANY );14-	15 	wxBoxSizer* bSizer2;16 	bSizer2 = new wxBoxSizer( wxVERTICAL );17 	18@@ -355,7 +354,6 @@19 	bSizer71 = new wxBoxSizer( wxHORIZONTAL );20 	21 	m_checkBoxLimitProcessors = new wxCheckBox( m_panelMain, wxID_ANY, _("&Limit coin generation to"), wxDefaultPosition, wxDefaultSize, 0 );22-	23 	bSizer71->Add( m_checkBoxLimitProcessors, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );24 	25 	m_spinCtrlLimitProcessors = new wxSpinCtrl( m_panelMain, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( 48,-1 ), wxSP_ARROW_KEYS, 1, 999, 1 );26@@ -368,22 +366,21 @@27 	bSizer69->Add( bSizer71, 0, 0, 5 );28 	29 	m_checkBoxStartOnSystemStartup = new wxCheckBox( m_panelMain, wxID_ANY, _("&Start Bitcoin on system startup"), wxDefaultPosition, wxDefaultSize, 0 );30-	31 	bSizer69->Add( m_checkBoxStartOnSystemStartup, 0, wxALL, 5 );32 	33 	m_checkBoxMinimizeToTray = new wxCheckBox( m_panelMain, wxID_ANY, _("&Minimize to the tray instead of the taskbar"), wxDefaultPosition, wxDefaultSize, 0 );34-	35 	bSizer69->Add( m_checkBoxMinimizeToTray, 0, wxALL, 5 );36 	37+	m_checkBoxUseUPnP = new wxCheckBox( m_panelMain, wxID_ANY, _("Map port using &UPnP"), wxDefaultPosition, wxDefaultSize, 0 );38+	bSizer69->Add( m_checkBoxUseUPnP, 0, wxALL, 5 );39+	40 	m_checkBoxMinimizeOnClose = new wxCheckBox( m_panelMain, wxID_ANY, _("M&inimize to the tray on close"), wxDefaultPosition, wxDefaultSize, 0 );41-	42 	bSizer69->Add( m_checkBoxMinimizeOnClose, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );43 	44 	wxBoxSizer* bSizer102;45 	bSizer102 = new wxBoxSizer( wxHORIZONTAL );46 	47 	m_checkBoxUseProxy = new wxCheckBox( m_panelMain, wxID_ANY, _("&Connect through socks4 proxy: "), wxDefaultPosition, wxDefaultSize, 0 );48-	49 	bSizer102->Add( m_checkBoxUseProxy, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );50 	51 	bSizer69->Add( bSizer102, 1, wxEXPAND, 5 );52@@ -550,7 +547,7 @@53 	54 	bSizer631->Add( 0, 4, 0, wxEXPAND, 5 );55 	56-	m_staticTextMain = new wxStaticText( this, wxID_ANY, _("Copyright (c) 2009-2010 Bitcoin Developers\n\nThis is experimental software.\n\nDistributed under the MIT/X11 software license, see the accompanying file \nlicense.txt or http://www.opensource.org/licenses/mit-license.php.\n\nThis product includes software developed by the OpenSSL Project for use in the \nOpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by \nEric Young (eay@cryptsoft.com)."), wxDefaultPosition, wxDefaultSize, 0 );57+	m_staticTextMain = new wxStaticText( this, wxID_ANY, _("Copyright (c) 2009-2011 Bitcoin Developers\n\nThis is experimental software.\n\nDistributed under the MIT/X11 software license, see the accompanying file \nlicense.txt or http://www.opensource.org/licenses/mit-license.php.\n\nThis product includes software developed by the OpenSSL Project for use in the \nOpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by \nEric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard."), wxDefaultPosition, wxDefaultSize, 0 );58 	m_staticTextMain->Wrap( -1 );59 	bSizer631->Add( m_staticTextMain, 0, wxALL, 5 );60 	61@@ -606,7 +603,7 @@62 	63 	fgSizer1->Add( 0, 0, 0, wxEXPAND, 5 );64 	65-	m_staticTextInstructions = new wxStaticText( this, wxID_ANY, _("Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJED9L) or IP address (e.g. 123.45.6.7)"), wxDefaultPosition, wxDefaultSize, 0 );66+	m_staticTextInstructions = new wxStaticText( this, wxID_ANY, _("Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)"), wxDefaultPosition, wxDefaultSize, 0 );67 	m_staticTextInstructions->Wrap( -1 );68 	fgSizer1->Add( m_staticTextInstructions, 0, wxTOP|wxRIGHT|wxLEFT, 5 );69 	70@@ -680,36 +677,7 @@71 	wxBoxSizer* bSizer672;72 	bSizer672 = new wxBoxSizer( wxHORIZONTAL );73 	74-	wxBoxSizer* bSizer681;75-	bSizer681 = new wxBoxSizer( wxVERTICAL );76-	77-	m_staticTextFrom = new wxStaticText( this, wxID_ANY, _("&From:"), wxDefaultPosition, wxDefaultSize, 0 );78-	m_staticTextFrom->Wrap( -1 );79-	bSizer681->Add( m_staticTextFrom, 0, wxBOTTOM|wxLEFT, 5 );80-	81-	m_textCtrlFrom = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( -1,-1 ), 0 );82-	bSizer681->Add( m_textCtrlFrom, 0, wxLEFT|wxEXPAND, 5 );83-	84-	bSizer672->Add( bSizer681, 1, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 );85-	86 	bSizer21->Add( bSizer672, 0, wxEXPAND, 5 );87-	88-	wxBoxSizer* bSizer67;89-	bSizer67 = new wxBoxSizer( wxHORIZONTAL );90-	91-	wxBoxSizer* bSizer68;92-	bSizer68 = new wxBoxSizer( wxVERTICAL );93-	94-	m_staticTextMessage = new wxStaticText( this, wxID_ANY, _("&Message:"), wxDefaultPosition, wxDefaultSize, 0 );95-	m_staticTextMessage->Wrap( -1 );96-	bSizer68->Add( m_staticTextMessage, 0, wxTOP|wxBOTTOM|wxLEFT, 5 );97-	98-	m_textCtrlMessage = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE );99-	bSizer68->Add( m_textCtrlMessage, 1, wxEXPAND|wxLEFT, 5 );100-	101-	bSizer67->Add( bSizer68, 1, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 );102-	103-	bSizer21->Add( bSizer67, 1, wxEXPAND, 5 );104 	105 	wxBoxSizer* bSizer23;106 	bSizer23 = new wxBoxSizer( wxHORIZONTAL );107@@ -737,8 +705,6 @@108 	m_buttonAddress->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( CSendDialogBase::OnButtonAddressBook ), NULL, this );109 	m_textCtrlAmount->Connect( wxEVT_KEY_DOWN, wxKeyEventHandler( CSendDialogBase::OnKeyDown ), NULL, this );110 	m_textCtrlAmount->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( CSendDialogBase::OnKillFocusAmount ), NULL, this );111-	m_textCtrlFrom->Connect( wxEVT_KEY_DOWN, wxKeyEventHandler( CSendDialogBase::OnKeyDown ), NULL, this );112-	m_textCtrlMessage->Connect( wxEVT_KEY_DOWN, wxKeyEventHandler( CSendDialogBase::OnKeyDown ), NULL, this );113 	m_buttonSend->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( CSendDialogBase::OnButtonSend ), NULL, this );114 	m_buttonCancel->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( CSendDialogBase::OnButtonCancel ), NULL, this );115 }116@@ -752,8 +718,6 @@117 	m_buttonAddress->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( CSendDialogBase::OnButtonAddressBook ), NULL, this );118 	m_textCtrlAmount->Disconnect( wxEVT_KEY_DOWN, wxKeyEventHandler( CSendDialogBase::OnKeyDown ), NULL, this );119 	m_textCtrlAmount->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( CSendDialogBase::OnKillFocusAmount ), NULL, this );120-	m_textCtrlFrom->Disconnect( wxEVT_KEY_DOWN, wxKeyEventHandler( CSendDialogBase::OnKeyDown ), NULL, this );121-	m_textCtrlMessage->Disconnect( wxEVT_KEY_DOWN, wxKeyEventHandler( CSendDialogBase::OnKeyDown ), NULL, this );122 	m_buttonSend->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( CSendDialogBase::OnButtonSend ), NULL, this );123 	m_buttonCancel->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( CSendDialogBase::OnButtonCancel ), NULL, this );124 }

uibase.h (modified)

1--- v0.3.20/uibase.h2+++ v0.3.21/uibase.h3@@ -1,5 +1,5 @@4 ///////////////////////////////////////////////////////////////////////////5-// C++ code generated with wxFormBuilder (version Apr 16 2008)6+// C++ code generated with wxFormBuilder (version Dec 21 2009)7 // http://www.wxformbuilder.org/8 //9 // PLEASE DO "NOT" EDIT THIS FILE!10@@ -93,28 +93,28 @@11 		wxPanel* m_panel93;12 		13 		// Virtual event handlers, overide them in your derived class14-		virtual void OnClose( wxCloseEvent& event ){ event.Skip(); }15-		virtual void OnIconize( wxIconizeEvent& event ){ event.Skip(); }16-		virtual void OnIdle( wxIdleEvent& event ){ event.Skip(); }17-		virtual void OnMouseEvents( wxMouseEvent& event ){ event.Skip(); }18-		virtual void OnPaint( wxPaintEvent& event ){ event.Skip(); }19-		virtual void OnMenuFileExit( wxCommandEvent& event ){ event.Skip(); }20-		virtual void OnMenuOptionsGenerate( wxCommandEvent& event ){ event.Skip(); }21-		virtual void OnUpdateUIOptionsGenerate( wxUpdateUIEvent& event ){ event.Skip(); }22-		virtual void OnMenuOptionsChangeYourAddress( wxCommandEvent& event ){ event.Skip(); }23-		virtual void OnMenuOptionsOptions( wxCommandEvent& event ){ event.Skip(); }24-		virtual void OnMenuHelpAbout( wxCommandEvent& event ){ event.Skip(); }25-		virtual void OnButtonSend( wxCommandEvent& event ){ event.Skip(); }26-		virtual void OnButtonAddressBook( wxCommandEvent& event ){ event.Skip(); }27-		virtual void OnKeyDown( wxKeyEvent& event ){ event.Skip(); }28-		virtual void OnMouseEventsAddress( wxMouseEvent& event ){ event.Skip(); }29-		virtual void OnSetFocusAddress( wxFocusEvent& event ){ event.Skip(); }30-		virtual void OnButtonNew( wxCommandEvent& event ){ event.Skip(); }31-		virtual void OnButtonCopy( wxCommandEvent& event ){ event.Skip(); }32-		virtual void OnNotebookPageChanged( wxNotebookEvent& event ){ event.Skip(); }33-		virtual void OnListColBeginDrag( wxListEvent& event ){ event.Skip(); }34-		virtual void OnListItemActivated( wxListEvent& event ){ event.Skip(); }35-		virtual void OnPaintListCtrl( wxPaintEvent& event ){ event.Skip(); }36+		virtual void OnClose( wxCloseEvent& event ) { event.Skip(); }37+		virtual void OnIconize( wxIconizeEvent& event ) { event.Skip(); }38+		virtual void OnIdle( wxIdleEvent& event ) { event.Skip(); }39+		virtual void OnMouseEvents( wxMouseEvent& event ) { event.Skip(); }40+		virtual void OnPaint( wxPaintEvent& event ) { event.Skip(); }41+		virtual void OnMenuFileExit( wxCommandEvent& event ) { event.Skip(); }42+		virtual void OnMenuOptionsGenerate( wxCommandEvent& event ) { event.Skip(); }43+		virtual void OnUpdateUIOptionsGenerate( wxUpdateUIEvent& event ) { event.Skip(); }44+		virtual void OnMenuOptionsChangeYourAddress( wxCommandEvent& event ) { event.Skip(); }45+		virtual void OnMenuOptionsOptions( wxCommandEvent& event ) { event.Skip(); }46+		virtual void OnMenuHelpAbout( wxCommandEvent& event ) { event.Skip(); }47+		virtual void OnButtonSend( wxCommandEvent& event ) { event.Skip(); }48+		virtual void OnButtonAddressBook( wxCommandEvent& event ) { event.Skip(); }49+		virtual void OnKeyDown( wxKeyEvent& event ) { event.Skip(); }50+		virtual void OnMouseEventsAddress( wxMouseEvent& event ) { event.Skip(); }51+		virtual void OnSetFocusAddress( wxFocusEvent& event ) { event.Skip(); }52+		virtual void OnButtonNew( wxCommandEvent& event ) { event.Skip(); }53+		virtual void OnButtonCopy( wxCommandEvent& event ) { event.Skip(); }54+		virtual void OnNotebookPageChanged( wxNotebookEvent& event ) { event.Skip(); }55+		virtual void OnListColBeginDrag( wxListEvent& event ) { event.Skip(); }56+		virtual void OnListItemActivated( wxListEvent& event ) { event.Skip(); }57+		virtual void OnPaintListCtrl( wxPaintEvent& event ) { event.Skip(); }58 		59 	60 	public:61@@ -125,6 +125,7 @@62 		wxListCtrl* m_listCtrlSentReceived;63 		wxListCtrl* m_listCtrlSent;64 		wxListCtrl* m_listCtrlReceived;65+		66 		CMainFrameBase( wxWindow* parent, wxWindowID id = wxID_MAINFRAME, const wxString& title = _("Bitcoin"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 723,484 ), long style = wxDEFAULT_FRAME_STYLE|wxRESIZE_BORDER|wxTAB_TRAVERSAL );67 		~CMainFrameBase();68 	69@@ -142,10 +143,11 @@70 		wxButton* m_buttonOK;71 		72 		// Virtual event handlers, overide them in your derived class73-		virtual void OnButtonOK( wxCommandEvent& event ){ event.Skip(); }74-		75-	76-	public:77+		virtual void OnButtonOK( wxCommandEvent& event ) { event.Skip(); }78+		79+	80+	public:81+		82 		CTxDetailsDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Transaction Details"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 620,450 ), long style = wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER );83 		~CTxDetailsDialogBase();84 	85@@ -168,6 +170,7 @@86 		wxStaticText* m_staticText35;87 		wxCheckBox* m_checkBoxStartOnSystemStartup;88 		wxCheckBox* m_checkBoxMinimizeToTray;89+		wxCheckBox* m_checkBoxUseUPnP;90 		wxCheckBox* m_checkBoxMinimizeOnClose;91 		wxCheckBox* m_checkBoxUseProxy;92 		93@@ -188,18 +191,19 @@94 		wxButton* m_buttonApply;95 		96 		// Virtual event handlers, overide them in your derived class97-		virtual void OnListBox( wxCommandEvent& event ){ event.Skip(); }98-		virtual void OnCheckBoxLimitProcessors( wxCommandEvent& event ){ event.Skip(); }99-		virtual void OnCheckBoxMinimizeToTray( wxCommandEvent& event ){ event.Skip(); }100-		virtual void OnCheckBoxUseProxy( wxCommandEvent& event ){ event.Skip(); }101-		virtual void OnKillFocusProxy( wxFocusEvent& event ){ event.Skip(); }102-		virtual void OnKillFocusTransactionFee( wxFocusEvent& event ){ event.Skip(); }103-		virtual void OnButtonOK( wxCommandEvent& event ){ event.Skip(); }104-		virtual void OnButtonCancel( wxCommandEvent& event ){ event.Skip(); }105-		virtual void OnButtonApply( wxCommandEvent& event ){ event.Skip(); }106-		107-	108-	public:109+		virtual void OnListBox( wxCommandEvent& event ) { event.Skip(); }110+		virtual void OnCheckBoxLimitProcessors( wxCommandEvent& event ) { event.Skip(); }111+		virtual void OnCheckBoxMinimizeToTray( wxCommandEvent& event ) { event.Skip(); }112+		virtual void OnCheckBoxUseProxy( wxCommandEvent& event ) { event.Skip(); }113+		virtual void OnKillFocusProxy( wxFocusEvent& event ) { event.Skip(); }114+		virtual void OnKillFocusTransactionFee( wxFocusEvent& event ) { event.Skip(); }115+		virtual void OnButtonOK( wxCommandEvent& event ) { event.Skip(); }116+		virtual void OnButtonCancel( wxCommandEvent& event ) { event.Skip(); }117+		virtual void OnButtonApply( wxCommandEvent& event ) { event.Skip(); }118+		119+	120+	public:121+		122 		COptionsDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Options"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 540,360 ), long style = wxDEFAULT_DIALOG_STYLE );123 		~COptionsDialogBase();124 	125@@ -223,11 +227,12 @@126 		wxButton* m_buttonOK;127 		128 		// Virtual event handlers, overide them in your derived class129-		virtual void OnButtonOK( wxCommandEvent& event ){ event.Skip(); }130+		virtual void OnButtonOK( wxCommandEvent& event ) { event.Skip(); }131 		132 	133 	public:134 		wxStaticText* m_staticTextVersion;135+		136 		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 );137 		~CAboutDialogBase();138 	139@@ -256,26 +261,23 @@140 		wxChoice* m_choiceTransferType;141 		142 		143-		wxStaticText* m_staticTextFrom;144-		wxTextCtrl* m_textCtrlFrom;145-		wxStaticText* m_staticTextMessage;146-		wxTextCtrl* m_textCtrlMessage;147 		148 		wxButton* m_buttonSend;149 		wxButton* m_buttonCancel;150 		151 		// Virtual event handlers, overide them in your derived class152-		virtual void OnKeyDown( wxKeyEvent& event ){ event.Skip(); }153-		virtual void OnTextAddress( wxCommandEvent& event ){ event.Skip(); }154-		virtual void OnButtonPaste( wxCommandEvent& event ){ event.Skip(); }155-		virtual void OnButtonAddressBook( wxCommandEvent& event ){ event.Skip(); }156-		virtual void OnKillFocusAmount( wxFocusEvent& event ){ event.Skip(); }157-		virtual void OnButtonSend( wxCommandEvent& event ){ event.Skip(); }158-		virtual void OnButtonCancel( wxCommandEvent& event ){ event.Skip(); }159-		160-	161-	public:162-		CSendDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Send Coins"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 675,298 ), long style = wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER );163+		virtual void OnKeyDown( wxKeyEvent& event ) { event.Skip(); }164+		virtual void OnTextAddress( wxCommandEvent& event ) { event.Skip(); }165+		virtual void OnButtonPaste( wxCommandEvent& event ) { event.Skip(); }166+		virtual void OnButtonAddressBook( wxCommandEvent& event ) { event.Skip(); }167+		virtual void OnKillFocusAmount( wxFocusEvent& event ) { event.Skip(); }168+		virtual void OnButtonSend( wxCommandEvent& event ) { event.Skip(); }169+		virtual void OnButtonCancel( wxCommandEvent& event ) { event.Skip(); }170+		171+	172+	public:173+		174+		CSendDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Send Coins"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 498,157 ), long style = wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER );175 		~CSendDialogBase();176 	177 };178@@ -295,13 +297,14 @@179 		wxButton* m_buttonCancel;180 		181 		// Virtual event handlers, overide them in your derived class182-		virtual void OnClose( wxCloseEvent& event ){ event.Skip(); }183-		virtual void OnPaint( wxPaintEvent& event ){ event.Skip(); }184-		virtual void OnButtonOK( wxCommandEvent& event ){ event.Skip(); }185-		virtual void OnButtonCancel( wxCommandEvent& event ){ event.Skip(); }186-		187-	188-	public:189+		virtual void OnClose( wxCloseEvent& event ) { event.Skip(); }190+		virtual void OnPaint( wxPaintEvent& event ) { event.Skip(); }191+		virtual void OnButtonOK( wxCommandEvent& event ) { event.Skip(); }192+		virtual void OnButtonCancel( wxCommandEvent& event ) { event.Skip(); }193+		194+	195+	public:196+		197 		CSendingDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Sending..."), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 442,151 ), long style = wxDEFAULT_DIALOG_STYLE );198 		~CSendingDialogBase();199 	200@@ -326,18 +329,19 @@201 		wxButton* m_buttonCancel;202 		203 		// Virtual event handlers, overide them in your derived class204-		virtual void OnClose( wxCloseEvent& event ){ event.Skip(); }205-		virtual void OnListEndLabelEdit( wxListEvent& event ){ event.Skip(); }206-		virtual void OnListItemActivated( wxListEvent& event ){ event.Skip(); }207-		virtual void OnListItemSelected( wxListEvent& event ){ event.Skip(); }208-		virtual void OnButtonRename( wxCommandEvent& event ){ event.Skip(); }209-		virtual void OnButtonNew( wxCommandEvent& event ){ event.Skip(); }210-		virtual void OnButtonCopy( wxCommandEvent& event ){ event.Skip(); }211-		virtual void OnButtonOK( wxCommandEvent& event ){ event.Skip(); }212-		virtual void OnButtonCancel( wxCommandEvent& event ){ event.Skip(); }213-		214-	215-	public:216+		virtual void OnClose( wxCloseEvent& event ) { event.Skip(); }217+		virtual void OnListEndLabelEdit( wxListEvent& event ) { event.Skip(); }218+		virtual void OnListItemActivated( wxListEvent& event ) { event.Skip(); }219+		virtual void OnListItemSelected( wxListEvent& event ) { event.Skip(); }220+		virtual void OnButtonRename( wxCommandEvent& event ) { event.Skip(); }221+		virtual void OnButtonNew( wxCommandEvent& event ) { event.Skip(); }222+		virtual void OnButtonCopy( wxCommandEvent& event ) { event.Skip(); }223+		virtual void OnButtonOK( wxCommandEvent& event ) { event.Skip(); }224+		virtual void OnButtonCancel( wxCommandEvent& event ) { event.Skip(); }225+		226+	227+	public:228+		229 		CYourAddressDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Your Bitcoin Addresses"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 610,390 ), long style = wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER );230 		~CYourAddressDialogBase();231 	232@@ -369,21 +373,22 @@233 		wxButton* m_buttonOK;234 		235 		// Virtual event handlers, overide them in your derived class236-		virtual void OnClose( wxCloseEvent& event ){ event.Skip(); }237-		virtual void OnNotebookPageChanged( wxNotebookEvent& event ){ event.Skip(); }238-		virtual void OnListEndLabelEdit( wxListEvent& event ){ event.Skip(); }239-		virtual void OnListItemActivated( wxListEvent& event ){ event.Skip(); }240-		virtual void OnListItemSelected( wxListEvent& event ){ event.Skip(); }241-		virtual void OnButtonDelete( wxCommandEvent& event ){ event.Skip(); }242-		virtual void OnButtonCopy( wxCommandEvent& event ){ event.Skip(); }243-		virtual void OnButtonEdit( wxCommandEvent& event ){ event.Skip(); }244-		virtual void OnButtonNew( wxCommandEvent& event ){ event.Skip(); }245-		virtual void OnButtonOK( wxCommandEvent& event ){ event.Skip(); }246-		virtual void OnButtonCancel( wxCommandEvent& event ){ event.Skip(); }247-		248-	249-	public:250-		wxButton* m_buttonCancel;251+		virtual void OnClose( wxCloseEvent& event ) { event.Skip(); }252+		virtual void OnNotebookPageChanged( wxNotebookEvent& event ) { event.Skip(); }253+		virtual void OnListEndLabelEdit( wxListEvent& event ) { event.Skip(); }254+		virtual void OnListItemActivated( wxListEvent& event ) { event.Skip(); }255+		virtual void OnListItemSelected( wxListEvent& event ) { event.Skip(); }256+		virtual void OnButtonDelete( wxCommandEvent& event ) { event.Skip(); }257+		virtual void OnButtonCopy( wxCommandEvent& event ) { event.Skip(); }258+		virtual void OnButtonEdit( wxCommandEvent& event ) { event.Skip(); }259+		virtual void OnButtonNew( wxCommandEvent& event ) { event.Skip(); }260+		virtual void OnButtonOK( wxCommandEvent& event ) { event.Skip(); }261+		virtual void OnButtonCancel( wxCommandEvent& event ) { event.Skip(); }262+		263+	264+	public:265+		wxButton* m_buttonCancel;266+		267 		CAddressBookDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Address Book"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 610,390 ), long style = wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER );268 		~CAddressBookDialogBase();269 	270@@ -408,13 +413,14 @@271 		wxButton* m_buttonCancel;272 		273 		// Virtual event handlers, overide them in your derived class274-		virtual void OnClose( wxCloseEvent& event ){ event.Skip(); }275-		virtual void OnKeyDown( wxKeyEvent& event ){ event.Skip(); }276-		virtual void OnButtonOK( wxCommandEvent& event ){ event.Skip(); }277-		virtual void OnButtonCancel( wxCommandEvent& event ){ event.Skip(); }278-		279-	280-	public:281+		virtual void OnClose( wxCloseEvent& event ) { event.Skip(); }282+		virtual void OnKeyDown( wxKeyEvent& event ) { event.Skip(); }283+		virtual void OnButtonOK( wxCommandEvent& event ) { event.Skip(); }284+		virtual void OnButtonCancel( wxCommandEvent& event ) { event.Skip(); }285+		286+	287+	public:288+		289 		CGetTextFromUserDialogBase( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 440,138 ), long style = wxDEFAULT_DIALOG_STYLE );290 		~CGetTextFromUserDialogBase();291 	

util.cpp (modified)

1--- v0.3.20/util.cpp2+++ v0.3.21/util.cpp3@@ -14,10 +14,12 @@4 bool fRequestShutdown = false;5 bool fShutdown = false;6 bool fDaemon = false;7+bool fServer = false;8 bool fCommandLine = false;9 string strMiscWarning;10 bool fTestNet = false;11 bool fNoListen = false;12+bool fLogTimestamps = false;13 14 15 16@@ -169,8 +171,16 @@17         }18         if (fileout)19         {20-            //// Debug print useful for profiling21-            //fprintf(fileout, " %"PRI64d" ", GetTimeMillis());22+            static bool fStartedNewLine = true;23+24+            // Debug print useful for profiling25+            if (fLogTimestamps && fStartedNewLine)26+                fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());27+            if (pszFormat[strlen(pszFormat) - 1] == '\n')28+                fStartedNewLine = true;29+            else30+                fStartedNewLine = false;31+32             va_list arg_ptr;33             va_start(arg_ptr, pszFormat);34             ret = vfprintf(fileout, pszFormat, arg_ptr);35@@ -313,9 +323,23 @@36 37 string FormatMoney(int64 n, bool fPlus)38 {39-    n /= CENT;40-    string str = strprintf("%"PRI64d".%02"PRI64d, (n > 0 ? n : -n)/100, (n > 0 ? n : -n)%100);41-    for (int i = 6; i < str.size(); i += 4)42+    // Note: not using straight sprintf here because we do NOT want43+    // localized number formatting.44+    int64 n_abs = (n > 0 ? n : -n);45+    int64 quotient = n_abs/COIN;46+    int64 remainder = n_abs%COIN;47+    string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);48+49+    // Right-trim excess 0's before the decimal point:50+    int nTrim = 0;51+    for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)52+        ++nTrim;53+    if (nTrim)54+        str.erase(str.size()-nTrim, nTrim);55+56+    // Insert thousands-separators:57+    size_t point = str.find(".");58+    for (int i = (str.size()-point)+3; i < str.size(); i += 4)59         if (isdigit(str[str.size() - i - 1]))60             str.insert(str.size() - i, 1, ',');61     if (n < 0)62@@ -334,7 +358,7 @@63 bool ParseMoney(const char* pszIn, int64& nRet)64 {65     string strWhole;66-    int64 nCents = 0;67+    int64 nUnits = 0;68     const char* p = pszIn;69     while (isspace(*p))70         p++;71@@ -345,11 +369,11 @@72         if (*p == '.')73         {74             p++;75-            if (isdigit(*p))76+            int64 nMult = CENT*10;77+            while (isdigit(*p) && (nMult > 0))78             {79-                nCents = 10 * (*p++ - '0');80-                if (isdigit(*p))81-                    nCents += (*p++ - '0');82+                nUnits += nMult * (*p++ - '0');83+                nMult /= 10;84             }85             break;86         }87@@ -364,15 +388,11 @@88             return false;89     if (strWhole.size() > 14)90         return false;91-    if (nCents < 0 || nCents > 99)92+    if (nUnits < 0 || nUnits > COIN)93         return false;94     int64 nWhole = atoi64(strWhole);95-    int64 nPreValue = nWhole * 100 + nCents;96-    int64 nValue = nPreValue * CENT;97-    if (nValue / CENT != nPreValue)98-        return false;99-    if (nValue / COIN != nWhole)100-        return false;101+    int64 nValue = nWhole*COIN + nUnits;102+103     nRet = nValue;104     return true;105 }106@@ -727,6 +747,25 @@107     }108 }109 110+string GetPidFile()111+{112+    namespace fs = boost::filesystem;113+    fs::path pathConfig(GetArg("-pid", "bitcoind.pid"));114+    if (!pathConfig.is_complete())115+        pathConfig = fs::path(GetDataDir()) / pathConfig;116+    return pathConfig.string();117+}118+119+void CreatePidFile(string pidFile, pid_t pid)120+{121+    FILE* file;122+    if (file = fopen(pidFile.c_str(), "w"))123+    {124+        fprintf(file, "%d\n", pid);125+        fclose(file);126+    }127+}128+129 int GetFilesize(FILE* file)130 {131     int nSavePos = ftell(file);132@@ -836,3 +875,32 @@133     }134 }135 136+137+138+139+140+141+142+143+144+string FormatVersion(int nVersion)145+{146+    if (nVersion%100 == 0)147+        return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);148+    else149+        return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);150+}151+152+string FormatFullVersion()153+{154+    string s = FormatVersion(VERSION) + pszSubVer;155+    if (VERSION_IS_BETA)156+        s += _("-beta");157+    return s;158+}159+160+161+162+163+164+

util.h (modified)

1--- v0.3.20/util.h2+++ v0.3.21/util.h3@@ -143,10 +143,12 @@4 extern bool fRequestShutdown;5 extern bool fShutdown;6 extern bool fDaemon;7+extern bool fServer;8 extern bool fCommandLine;9 extern string strMiscWarning;10 extern bool fTestNet;11 extern bool fNoListen;12+extern bool fLogTimestamps;13 14 void RandAddSeed();15 void RandAddSeedPerfmon();16@@ -170,6 +172,8 @@17 int GetFilesize(FILE* file);18 void GetDataDir(char* pszDirRet);19 string GetConfigFile();20+string GetPidFile();21+void CreatePidFile(string pidFile, pid_t pid);22 void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet);23 #ifdef __WXMSW__24 string MyGetSpecialFolderPath(int nFolder, bool fCreate);25@@ -182,6 +186,7 @@26 int64 GetTime();27 int64 GetAdjustedTime();28 void AddTimeData(unsigned int ip, int64 nTime);29+string FormatFullVersion();30 31 32 33@@ -427,14 +432,6 @@34         return (atoi(mapArgs[strArg]) != 0);35     }36     return false;37-}38-39-inline string FormatVersion(int nVersion)40-{41-    if (nVersion%100 == 0)42-        return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);43-    else44-        return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);45 }46 47 
0:000:00