command line and JSON-RPC first draft, requires Boost 1.35 or higher for boost::asio,
authors_nakamoto <s_nakamoto@1a98c847-1fd6-4fd8-948a-caf3550aa51b>
Fri, 12 Feb 2010 20:38:44 +0000 (20:38 +0000)
committers_nakamoto <s_nakamoto@1a98c847-1fd6-4fd8-948a-caf3550aa51b>
Fri, 12 Feb 2010 20:38:44 +0000 (20:38 +0000)
added SetBitcoinAddress and GetBitcoinAddress methods on CScript,
critsect interlocks around mapAddressBook,
added some random delays in tx broadcast to improve privacy,
now compiles with MSVC 8.0

git-svn-id: https://bitcoin.svn.sourceforge.net/svnroot/bitcoin/trunk@60 1a98c847-1fd6-4fd8-948a-caf3550aa51b

23 files changed:
bignum.h
build-msw.txt
db.h
headers.h
irc.cpp
irc.h
license.txt
main.cpp
main.h
makefile
makefile.unix.wx2.8
makefile.unix.wx2.9
makefile.vc
net.cpp
net.h
rpc.cpp [new file with mode: 0644]
rpc.h [new file with mode: 0644]
script.cpp
script.h
serialize.h
ui.cpp
util.cpp
util.h

index 8aa4e9c..e1ab165 100644 (file)
--- a/bignum.h
+++ b/bignum.h
@@ -1,4 +1,4 @@
-// Copyright (c) 2009 Satoshi Nakamoto\r
+// Copyright (c) 2009-2010 Satoshi Nakamoto\r
 // Distributed under the MIT/X11 software license, see the accompanying\r
 // file license.txt or http://www.opensource.org/licenses/mit-license.php.\r
 \r
@@ -309,6 +309,37 @@ public:
             *this = 0 - *this;\r
     }\r
 \r
+    std::string ToString(int nBase=10) const\r
+    {\r
+        CAutoBN_CTX pctx;\r
+        CBigNum bnBase = nBase;\r
+        CBigNum bn0 = 0;\r
+        string str;\r
+        CBigNum bn = *this;\r
+        BN_set_negative(&bn, false);\r
+        CBigNum dv;\r
+        CBigNum rem;\r
+        if (BN_cmp(&bn, &bn0) == 0)\r
+            return "0";\r
+        while (BN_cmp(&bn, &bn0) > 0)\r
+        {\r
+            if (!BN_div(&dv, &rem, &bn, &bnBase, pctx))\r
+                throw bignum_error("CBigNum::ToString() : BN_div failed");\r
+            bn = dv;\r
+            unsigned int c = rem.getulong();\r
+            str += "0123456789abcdef"[c];\r
+        }\r
+        if (BN_is_negative(this))\r
+            str += "-";\r
+        reverse(str.begin(), str.end());\r
+        return str;\r
+    }\r
+\r
+    std::string GetHex() const\r
+    {\r
+        return ToString(16);\r
+    }\r
+\r
     unsigned int GetSerializeSize(int nType=0, int nVersion=VERSION) const\r
     {\r
         return ::GetSerializeSize(getvch(), nType, nVersion);\r
index 56a38b0..9786255 100644 (file)
@@ -1,6 +1,6 @@
 Bitcoin v0.2.0 BETA\r
 \r
-Copyright (c) 2009 Satoshi Nakamoto\r
+Copyright (c) 2009-2010 Satoshi Nakamoto\r
 Distributed under the MIT/X11 software license, see the accompanying\r
 file license.txt or http://www.opensource.org/licenses/mit-license.php.\r
 This product includes software developed by the OpenSSL Project for use in\r
@@ -13,8 +13,16 @@ WINDOWS BUILD NOTES
 \r
 Compilers Supported\r
 -------------------\r
-MinGW GCC\r
-Microsoft Visual C++ 6.0 SP6\r
+MinGW GCC (recommended)\r
+\r
+MSVC 6.0 SP6: You'll need Boost version 1.34 because they dropped support\r
+for MSVC 6.0 after that.  However, they didn't add Asio until 1.35.\r
+You should still be able to build with MSVC 6.0 by adding Asio to 1.34 by\r
+unpacking boost_asio_*.zip into the boost directory:\r
+http://sourceforge.net/projects/asio/files/asio\r
+\r
+MSVC 8.0 (2005) SP1 has been tested.  Note: MSVC 7.0 and up have a habit of\r
+linking to runtime DLLs that are not installed on XP by default.\r
 \r
 \r
 Dependencies\r
@@ -22,8 +30,7 @@ Dependencies
 Libraries you need to download separately and build:\r
 \r
               default path   download\r
-wxWidgets      \wxwidgets     http://www.wxwidgets.org/downloads/\r
-                                or prebuilt: http://wxpack.sourceforge.net\r
+wxWidgets      \wxwidgets     prebuilt: http://wxpack.sourceforge.net\r
 OpenSSL        \openssl       http://www.openssl.org/source/\r
 Berkeley DB    \db            http://www.oracle.com/technology/software/products/berkeley-db/index.html\r
 Boost          \boost         http://www.boost.org/users/download/\r
@@ -89,3 +96,13 @@ Using MinGW and MSYS:
 cd \db\build_unix\r
 sh ../dist/configure --enable-mingw --enable-cxx\r
 make\r
+\r
+\r
+Boost\r
+-----\r
+download bjam.exe from\r
+http://sourceforge.net/project/showfiles.php?group_id=7586&package_id=72941\r
+cd \boost\r
+bjam toolset=gcc --build-type=complete stage\r
+or\r
+bjam toolset=msvc --build-type=complete stage\r
diff --git a/db.h b/db.h
index d32d2d5..538076b 100644 (file)
--- a/db.h
+++ b/db.h
@@ -1,8 +1,7 @@
-// Copyright (c) 2009 Satoshi Nakamoto\r
+// Copyright (c) 2009-2010 Satoshi Nakamoto\r
 // Distributed under the MIT/X11 software license, see the accompanying\r
 // file license.txt or http://www.opensource.org/licenses/mit-license.php.\r
 \r
-#include <db_cxx.h>\r
 class CTransaction;\r
 class CTxIndex;\r
 class CDiskBlockIndex;\r
@@ -14,6 +13,7 @@ class CAddress;
 class CWalletTx;\r
 \r
 extern map<string, string> mapAddressBook;\r
+extern CCriticalSection cs_mapAddressBook;\r
 extern bool fClient;\r
 \r
 \r
@@ -359,15 +359,17 @@ public:
 \r
     bool WriteName(const string& strAddress, const string& strName)\r
     {\r
+        CRITICAL_BLOCK(cs_mapAddressBook)\r
+            mapAddressBook[strAddress] = strName;\r
         nWalletDBUpdated++;\r
-        mapAddressBook[strAddress] = strName;\r
         return Write(make_pair(string("name"), strAddress), strName);\r
     }\r
 \r
     bool EraseName(const string& strAddress)\r
     {\r
+        CRITICAL_BLOCK(cs_mapAddressBook)\r
+            mapAddressBook.erase(strAddress);\r
         nWalletDBUpdated++;\r
-        mapAddressBook.erase(strAddress);\r
         return Erase(make_pair(string("name"), strAddress));\r
     }\r
 \r
index 45be4b6..dda4f9c 100644 (file)
--- a/headers.h
+++ b/headers.h
@@ -29,6 +29,7 @@
 #include <openssl/rand.h>\r
 #include <openssl/sha.h>\r
 #include <openssl/ripemd.h>\r
+#include <db_cxx.h>\r
 #include <stdio.h>\r
 #include <stdlib.h>\r
 #include <math.h>\r
@@ -36,6 +37,7 @@
 #include <float.h>\r
 #include <assert.h>\r
 #include <memory>\r
+#include <iostream>\r
 #include <sstream>\r
 #include <string>\r
 #include <vector>\r
@@ -53,6 +55,8 @@
 #include <boost/array.hpp>\r
 #include <boost/bind.hpp>\r
 #include <boost/function.hpp>\r
+#include <boost/filesystem.hpp>\r
+#include <boost/algorithm/string.hpp>\r
 \r
 #ifdef __WXMSW__\r
 #include <windows.h>\r
@@ -73,8 +77,6 @@
 #include <errno.h>\r
 #include <net/if.h>\r
 #include <ifaddrs.h>\r
-#include <boost/filesystem.hpp>\r
-#include <boost/algorithm/string.hpp>\r
 #endif\r
 #ifdef __BSD__\r
 #include <netinet/in.h>\r
@@ -85,8 +87,6 @@
 using namespace std;\r
 using namespace boost;\r
 \r
-\r
-\r
 #include "strlcpy.h"\r
 #include "serialize.h"\r
 #include "uint256.h"\r
@@ -100,6 +100,7 @@ using namespace boost;
 #include "irc.h"\r
 #include "main.h"\r
 #include "market.h"\r
+#include "rpc.h"\r
 #include "uibase.h"\r
 #include "ui.h"\r
 \r
diff --git a/irc.cpp b/irc.cpp
index f38db6b..9d563cc 100644 (file)
--- a/irc.cpp
+++ b/irc.cpp
@@ -1,4 +1,4 @@
-// Copyright (c) 2009 Satoshi Nakamoto\r
+// Copyright (c) 2009-2010 Satoshi Nakamoto\r
 // Distributed under the MIT/X11 software license, see the accompanying\r
 // file license.txt or http://www.opensource.org/licenses/mit-license.php.\r
 \r
diff --git a/irc.h b/irc.h
index c69fd9e..13de570 100644 (file)
--- a/irc.h
+++ b/irc.h
@@ -1,8 +1,8 @@
-// Copyright (c) 2009 Satoshi Nakamoto\r
+// Copyright (c) 2009-2010 Satoshi Nakamoto\r
 // Distributed under the MIT/X11 software license, see the accompanying\r
 // file license.txt or http://www.opensource.org/licenses/mit-license.php.\r
 \r
-extern bool RecvLine(SOCKET hSocket, string& strLine);\r
-extern void ThreadIRCSeed(void* parg);\r
+bool RecvLine(SOCKET hSocket, string& strLine);\r
+void ThreadIRCSeed(void* parg);\r
 \r
 extern int nGotIRCAddresses;\r
index 3844dfb..f96fa98 100644 (file)
@@ -1,4 +1,4 @@
-Copyright (c) 2009 Satoshi Nakamoto\r
+Copyright (c) 2009-2010 Satoshi Nakamoto\r
 \r
 Permission is hereby granted, free of charge, to any person obtaining a copy\r
 of this software and associated documentation files (the "Software"), to deal\r
index 53acf8a..90d239f 100644 (file)
--- a/main.cpp
+++ b/main.cpp
@@ -26,6 +26,7 @@ CBlockIndex* pindexGenesisBlock = NULL;
 int nBestHeight = -1;\r
 uint256 hashBestChain = 0;\r
 CBlockIndex* pindexBest = NULL;\r
+int64 nTimeBestReceived = 0;\r
 \r
 map<uint256, CBlock*> mapOrphanBlocks;\r
 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;\r
@@ -45,6 +46,9 @@ CKey keyUser;
 map<uint256, int> mapRequestCount;\r
 CCriticalSection cs_mapRequestCount;\r
 \r
+map<string, string> mapAddressBook;\r
+CCriticalSection cs_mapAddressBook;\r
+\r
 // Settings\r
 int fGenerateBitcoins = false;\r
 int64 nTransactionFee = 0;\r
@@ -573,7 +577,7 @@ bool CTransaction::RemoveFromMemoryPool()
 \r
 \r
 \r
-int CMerkleTx::GetDepthInMainChain() const\r
+int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const\r
 {\r
     if (hashBlock == 0 || nIndex == -1)\r
         return 0;\r
@@ -594,6 +598,7 @@ int CMerkleTx::GetDepthInMainChain() const
         fMerkleVerified = true;\r
     }\r
 \r
+    nHeightRet = pindex->nHeight;\r
     return pindexBest->nHeight - pindex->nHeight + 1;\r
 }\r
 \r
@@ -708,15 +713,20 @@ void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
     }\r
 }\r
 \r
-void RelayWalletTransactions()\r
+void ResendWalletTransactions()\r
 {\r
-    static int64 nLastTime;\r
-    if (GetTime() - nLastTime < 10 * 60)\r
+    // Do this infrequently and randomly to avoid giving away\r
+    // that these are our transactions.\r
+    static int64 nNextTime;\r
+    if (GetTime() < nNextTime)\r
+        return;\r
+    bool fFirst = (nNextTime == 0);\r
+    nNextTime = GetTime() + GetRand(120 * 60);\r
+    if (fFirst)\r
         return;\r
-    nLastTime = GetTime();\r
 \r
     // Rebroadcast any of our txes that aren't in a block yet\r
-    printf("RelayWalletTransactions()\n");\r
+    printf("ResendWalletTransactions()\n");\r
     CTxDB txdb("r");\r
     CRITICAL_BLOCK(cs_mapWallet)\r
     {\r
@@ -725,7 +735,10 @@ void RelayWalletTransactions()
         foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)\r
         {\r
             CWalletTx& wtx = item.second;\r
-            mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));\r
+            // Don't rebroadcast until it's had plenty of time that\r
+            // it should have gotten in already by now.\r
+            if (nTimeBestReceived - wtx.nTimeReceived > 60 * 60)\r
+                mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));\r
         }\r
         foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)\r
         {\r
@@ -1219,10 +1232,11 @@ bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
             }\r
         }\r
 \r
-        // New best link\r
+        // New best block\r
         hashBestChain = hash;\r
         pindexBest = pindexNew;\r
         nBestHeight = pindexBest->nHeight;\r
+        nTimeBestReceived = GetTime();\r
         nTransactionsUpdated++;\r
         printf("AddToBlockIndex: new best=%s  height=%d\n", hashBestChain.ToString().substr(0,16).c_str(), nBestHeight);\r
     }\r
@@ -1232,9 +1246,6 @@ bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
 \r
     if (pindexNew == pindexBest)\r
     {\r
-        // Relay wallet transactions that haven't gotten in yet\r
-        RelayWalletTransactions();\r
-\r
         // Notify UI to display prev block's coinbase if it was ours\r
         static uint256 hashPrevBestCoinBase;\r
         CRITICAL_BLOCK(cs_mapWallet)\r
@@ -2248,7 +2259,7 @@ bool SendMessages(CNode* pto)
             return true;\r
 \r
         // Keep-alive ping\r
-        if (pto->nLastSend && GetTime() - pto->nLastSend > 12 * 60 && pto->vSend.empty())\r
+        if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())\r
             pto->PushMessage("ping");\r
 \r
         // Address refresh broadcast\r
@@ -2270,60 +2281,81 @@ bool SendMessages(CNode* pto)
             }\r
         }\r
 \r
+        // Delay tx inv messages to protect privacy,\r
+        // trickle them out to a few nodes at a time.\r
+        bool fSendTxInv = false;\r
+        if (GetTimeMillis() - pto->nLastSentTxInv > 1800 + GetRand(200))\r
+        {\r
+            pto->nLastSentTxInv = GetTimeMillis();\r
+            fSendTxInv = true;\r
+        }\r
+\r
+        // Resend wallet transactions that haven't gotten in a block yet\r
+        ResendWalletTransactions();\r
+\r
 \r
         //\r
         // Message: addr\r
         //\r
-        vector<CAddress> vAddrToSend;\r
-        vAddrToSend.reserve(pto->vAddrToSend.size());\r
+        vector<CAddress> vAddr;\r
+        vAddr.reserve(pto->vAddrToSend.size());\r
         foreach(const CAddress& addr, pto->vAddrToSend)\r
         {\r
             // returns true if wasn't already contained in the set\r
             if (pto->setAddrKnown.insert(addr).second)\r
             {\r
-                vAddrToSend.push_back(addr);\r
-                if (vAddrToSend.size() >= 1000)\r
+                vAddr.push_back(addr);\r
+                if (vAddr.size() >= 1000)\r
                 {\r
-                    pto->PushMessage("addr", vAddrToSend);\r
-                    vAddrToSend.clear();\r
+                    pto->PushMessage("addr", vAddr);\r
+                    vAddr.clear();\r
                 }\r
             }\r
         }\r
         pto->vAddrToSend.clear();\r
-        if (!vAddrToSend.empty())\r
-            pto->PushMessage("addr", vAddrToSend);\r
+        if (!vAddr.empty())\r
+            pto->PushMessage("addr", vAddr);\r
 \r
 \r
         //\r
         // Message: inventory\r
         //\r
-        vector<CInv> vInventoryToSend;\r
+        vector<CInv> vInv;\r
+        vector<CInv> vInvWait;\r
         CRITICAL_BLOCK(pto->cs_inventory)\r
         {\r
-            vInventoryToSend.reserve(pto->vInventoryToSend.size());\r
+            vInv.reserve(pto->vInventoryToSend.size());\r
+            vInvWait.reserve(pto->vInventoryToSend.size());\r
             foreach(const CInv& inv, pto->vInventoryToSend)\r
             {\r
+                // delay txes\r
+                if (!fSendTxInv && inv.type == MSG_TX)\r
+                {\r
+                    vInvWait.push_back(inv);\r
+                    continue;\r
+                }\r
+\r
                 // returns true if wasn't already contained in the set\r
                 if (pto->setInventoryKnown.insert(inv).second)\r
                 {\r
-                    vInventoryToSend.push_back(inv);\r
-                    if (vInventoryToSend.size() >= 1000)\r
+                    vInv.push_back(inv);\r
+                    if (vInv.size() >= 1000)\r
                     {\r
-                        pto->PushMessage("inv", vInventoryToSend);\r
-                        vInventoryToSend.clear();\r
+                        pto->PushMessage("inv", vInv);\r
+                        vInv.clear();\r
                     }\r
                 }\r
             }\r
-            pto->vInventoryToSend.clear();\r
+            pto->vInventoryToSend = vInvWait;\r
         }\r
-        if (!vInventoryToSend.empty())\r
-            pto->PushMessage("inv", vInventoryToSend);\r
+        if (!vInv.empty())\r
+            pto->PushMessage("inv", vInv);\r
 \r
 \r
         //\r
         // Message: getdata\r
         //\r
-        vector<CInv> vAskFor;\r
+        vector<CInv> vGetData;\r
         int64 nNow = GetTime() * 1000000;\r
         CTxDB txdb("r");\r
         while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)\r
@@ -2332,17 +2364,17 @@ bool SendMessages(CNode* pto)
             if (!AlreadyHave(txdb, inv))\r
             {\r
                 printf("sending getdata: %s\n", inv.ToString().c_str());\r
-                vAskFor.push_back(inv);\r
-                if (vAskFor.size() >= 1000)\r
+                vGetData.push_back(inv);\r
+                if (vGetData.size() >= 1000)\r
                 {\r
-                    pto->PushMessage("getdata", vAskFor);\r
-                    vAskFor.clear();\r
+                    pto->PushMessage("getdata", vGetData);\r
+                    vGetData.clear();\r
                 }\r
             }\r
             pto->mapAskFor.erase(pto->mapAskFor.begin());\r
         }\r
-        if (!vAskFor.empty())\r
-            pto->PushMessage("getdata", vAskFor);\r
+        if (!vGetData.empty())\r
+            pto->PushMessage("getdata", vGetData);\r
 \r
     }\r
     return true;\r
@@ -2405,7 +2437,6 @@ void ThreadBitcoinMiner(void* parg)
         vnThreadsRunning[3]--;\r
         PrintException(NULL, "ThreadBitcoinMiner()");\r
     }\r
-\r
     printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);\r
 }\r
 \r
@@ -2842,6 +2873,13 @@ bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CK
                 // Fill a vout back to self with any change\r
                 if (nValueIn > nTotalValue)\r
                 {\r
+                    // Note: We use a new key here to keep it from being obvious which side is the change.\r
+                    //  The drawback is that by not reusing a previous key, the change may be lost if a\r
+                    //  backup is restored, if the backup doesn't have the new private key for the change.\r
+                    //  If we reused the old key, it would be possible to add code to look for and\r
+                    //  rediscover unknown transactions that were written with keys of ours to recover\r
+                    //  post-backup change.\r
+\r
                     // New private key\r
                     if (keyRet.IsNull())\r
                         keyRet.MakeNewKey();\r
@@ -2899,7 +2937,7 @@ bool CommitTransactionSpent(const CWalletTx& wtxNew, const CKey& key)
         //// update: This matters even less now that fSpent can get corrected\r
         ////  when transactions are seen in VerifySignature.  The remote chance of\r
         ////  unmarked fSpent will be handled by that.  Don't need to make this\r
-        ////  transactional.\r
+        ////  transactional.  Pls delete this comment block later.\r
 \r
         // This is only to keep the database open to defeat the auto-flush for the\r
         // duration of this scope.  This is the only place where this optimization\r
@@ -2932,7 +2970,7 @@ bool CommitTransactionSpent(const CWalletTx& wtxNew, const CKey& key)
 \r
 \r
 \r
-bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew)\r
+string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew)\r
 {\r
     CRITICAL_BLOCK(cs_main)\r
     {\r
@@ -2945,13 +2983,13 @@ bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew)
                 strError = strprintf("Error: This is an oversized transaction that requires a transaction fee of %s  ", FormatMoney(nFeeRequired).c_str());\r
             else\r
                 strError = "Error: Transaction creation failed  ";\r
-            wxMessageBox(strError, "Sending...");\r
-            return error("SendMoney() : %s", strError.c_str());\r
+            printf("SendMoney() : %s", strError.c_str());\r
+            return strError;\r
         }\r
         if (!CommitTransactionSpent(wtxNew, key))\r
         {\r
-            wxMessageBox("Error finalizing transaction  ", "Sending...");\r
-            return error("SendMoney() : Error finalizing transaction");\r
+            printf("SendMoney() : Error finalizing transaction");\r
+            return "Error finalizing transaction";\r
         }\r
 \r
         // Track how many getdata requests our transaction gets\r
@@ -2964,11 +3002,32 @@ bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew)
         if (!wtxNew.AcceptTransaction())\r
         {\r
             // This must not fail. The transaction has already been signed and recorded.\r
-            wxMessageBox("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.", "Sending...");\r
-            return error("SendMoney() : Error: Transaction not valid");\r
+            printf("SendMoney() : Error: Transaction not valid");\r
+            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.";\r
         }\r
         wtxNew.RelayWalletTransaction();\r
     }\r
     MainFrameRepaint();\r
-    return true;\r
+    return "";\r
+}\r
+\r
+\r
+\r
+string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew)\r
+{\r
+    // Check amount\r
+    if (nValue <= 0)\r
+        return "Invalid amount";\r
+    if (nValue + nTransactionFee > GetBalance())\r
+        return "You don't have enough money";\r
+\r
+    // Parse bitcoin address\r
+    uint160 hash160;\r
+    if (!AddressToHash160(strAddress, hash160))\r
+        return "Invalid bitcoin address";\r
+\r
+    // Send to bitcoin address\r
+    CScript scriptPubKey;\r
+    scriptPubKey.SetBitcoinAddress(hash160);\r
+    return SendMoney(scriptPubKey, nValue, wtxNew);\r
 }\r
diff --git a/main.h b/main.h
index 14c445c..bcb6ec7 100644 (file)
--- a/main.h
+++ b/main.h
@@ -36,6 +36,8 @@ extern CBlockIndex* pindexBest;
 extern unsigned int nTransactionsUpdated;\r
 extern map<uint256, int> mapRequestCount;\r
 extern CCriticalSection cs_mapRequestCount;\r
+extern map<string, string> mapAddressBook;\r
+extern CCriticalSection cs_mapAddressBook;\r
 \r
 // Settings\r
 extern int fGenerateBitcoins;\r
@@ -58,7 +60,6 @@ vector<unsigned char> GenerateNewKey();
 bool AddToWallet(const CWalletTx& wtxIn);\r
 void WalletUpdateSpent(const COutPoint& prevout);\r
 void ReacceptWalletTransactions();\r
-void RelayWalletTransactions();\r
 bool LoadBlockIndex(bool fAllowNew=true);\r
 void PrintBlockTree();\r
 bool ProcessMessages(CNode* pfrom);\r
@@ -67,7 +68,8 @@ bool SendMessages(CNode* pto);
 int64 GetBalance();\r
 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet);\r
 bool CommitTransactionSpent(const CWalletTx& wtxNew, const CKey& key);\r
-bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew);\r
+string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew);\r
+string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew);\r
 void GenerateBitcoins(bool fGenerate);\r
 void ThreadBitcoinMiner(void* parg);\r
 void BitcoinMiner();\r
@@ -680,7 +682,8 @@ public:
 \r
 \r
     int SetMerkleBranch(const CBlock* pblock=NULL);\r
-    int GetDepthInMainChain() const;\r
+    int GetDepthInMainChain(int& nHeightRet) const;\r
+    int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }\r
     bool IsInMainChain() const { return GetDepthInMainChain() > 0; }\r
     int GetBlocksToMaturity() const;\r
     bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);\r
index 0dd6221..affbe51 100644 (file)
--- a/makefile
+++ b/makefile
@@ -1,4 +1,4 @@
-# Copyright (c) 2009 Satoshi Nakamoto\r
+# Copyright (c) 2009-2010 Satoshi Nakamoto\r
 # Distributed under the MIT/X11 software license, see the accompanying\r
 # file license.txt or http://www.opensource.org/licenses/mit-license.php.\r
 \r
@@ -16,22 +16,23 @@ endif
 \r
 \r
 INCLUDEPATHS=-I"/boost" -I"/db/build_unix" -I"/openssl/include" -I"/wxwidgets/lib/vc_lib/mswd" -I"/wxwidgets/include"\r
-LIBPATHS=-L"/db/build_unix" -L"/openssl/out" -L"/wxwidgets/lib/gcc_lib"\r
+LIBPATHS=-L"/boost/stage/lib" -L"/db/build_unix" -L"/openssl/out" -L"/wxwidgets/lib/gcc_lib"\r
 LIBS= \\r
+ -l libboost_system-mgw34-mt-d -l libboost_filesystem-mgw34-mt-d \\r
  -l db_cxx \\r
  -l eay32 \\r
  -l wxmsw28$(D)_richtext -l wxmsw28$(D)_html -l wxmsw28$(D)_core -l wxmsw28$(D)_adv -l wxbase28$(D) -l wxtiff$(D) -l wxjpeg$(D) -l wxpng$(D) -l wxzlib$(D) -l wxregex$(D) -l wxexpat$(D) \\r
  -l kernel32 -l user32 -l gdi32 -l comdlg32 -l winspool -l winmm -l shell32 -l comctl32 -l ole32 -l oleaut32 -l uuid -l rpcrt4 -l advapi32 -l ws2_32 -l shlwapi\r
 WXDEFS=-DWIN32 -D__WXMSW__ -D_WINDOWS -DNOPCH\r
 CFLAGS=-mthreads -O0 -w -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(WXDEFS) $(INCLUDEPATHS)\r
-HEADERS=headers.h util.h main.h serialize.h uint256.h key.h bignum.h script.h db.h base58.h\r
+HEADERS=headers.h strlcpy.h serialize.h uint256.h util.h key.h bignum.h base58.h script.h db.h net.h irc.h main.h market.h rpc.h uibase.h ui.h\r
 \r
 \r
 \r
 all: bitcoin.exe\r
 \r
 \r
-headers.h.gch: headers.h $(HEADERS) net.h irc.h market.h uibase.h ui.h\r
+headers.h.gch: headers.h            $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
 obj/util.o: util.cpp                $(HEADERS)\r
@@ -40,19 +41,19 @@ obj/util.o: util.cpp                $(HEADERS)
 obj/script.o: script.cpp            $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
-obj/db.o: db.cpp                    $(HEADERS) market.h\r
+obj/db.o: db.cpp                    $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
-obj/net.o: net.cpp                  $(HEADERS) net.h\r
+obj/net.o: net.cpp                  $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
-obj/main.o: main.cpp                $(HEADERS) net.h market.h sha.h\r
+obj/main.o: main.cpp                $(HEADERS) sha.h\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
-obj/market.o: market.cpp            $(HEADERS) market.h\r
+obj/market.o: market.cpp            $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
-obj/ui.o: ui.cpp                    $(HEADERS) net.h uibase.h ui.h market.h\r
+obj/ui.o: ui.cpp                    $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
 obj/uibase.o: uibase.cpp            uibase.h\r
@@ -64,13 +65,17 @@ obj/sha.o: sha.cpp                  sha.h
 obj/irc.o: irc.cpp                  $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
+obj/rpc.o: rpc.cpp                  $(HEADERS)\r
+       g++ -c $(CFLAGS) -o $@ $<\r
+\r
 obj/ui_res.o: ui.rc  rc/bitcoin.ico rc/check.ico rc/send16.bmp rc/send16mask.bmp rc/send16masknoshadow.bmp rc/send20.bmp rc/send20mask.bmp rc/addressbook16.bmp rc/addressbook16mask.bmp rc/addressbook20.bmp rc/addressbook20mask.bmp\r
        windres $(WXDEFS) $(INCLUDEPATHS) -o $@ -i $<\r
 \r
 \r
 \r
 OBJS=obj/util.o obj/script.o obj/db.o obj/net.o obj/main.o obj/market.o \\r
-        obj/ui.o obj/uibase.o obj/sha.o obj/irc.o obj/ui_res.o\r
+        obj/ui.o obj/uibase.o obj/sha.o obj/irc.o obj/rpc.o \\r
+        obj/ui_res.o\r
 \r
 bitcoin.exe: headers.h.gch $(OBJS)\r
        -kill /f bitcoin.exe\r
index b9826d6..d3358ab 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright (c) 2009 Satoshi Nakamoto\r
+# Copyright (c) 2009-2010 Satoshi Nakamoto\r
 # Distributed under the MIT/X11 software license, see the accompanying\r
 # file license.txt or http://www.opensource.org/licenses/mit-license.php.\r
 \r
@@ -35,14 +35,14 @@ LIBS= \
 \r
 WXDEFS=-D__WXGTK__ -DNOPCH\r
 CFLAGS=-O0 -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(WXDEFS) $(INCLUDEPATHS)\r
-HEADERS=headers.h util.h main.h serialize.h uint256.h key.h bignum.h script.h db.h base58.h\r
+HEADERS=headers.h strlcpy.h serialize.h uint256.h util.h key.h bignum.h base58.h script.h db.h net.h irc.h main.h market.h rpc.h uibase.h ui.h\r
 \r
 \r
 \r
 all: bitcoin\r
 \r
 \r
-headers.h.gch: headers.h $(HEADERS) net.h irc.h market.h uibase.h ui.h\r
+headers.h.gch: headers.h            $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
 obj/util.o: util.cpp                $(HEADERS)\r
@@ -51,19 +51,19 @@ obj/util.o: util.cpp                $(HEADERS)
 obj/script.o: script.cpp            $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
-obj/db.o: db.cpp                    $(HEADERS) market.h\r
+obj/db.o: db.cpp                    $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
-obj/net.o: net.cpp                  $(HEADERS) net.h\r
+obj/net.o: net.cpp                  $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
-obj/main.o: main.cpp                $(HEADERS) net.h market.h sha.h\r
+obj/main.o: main.cpp                $(HEADERS) sha.h\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
-obj/market.o: market.cpp            $(HEADERS) market.h\r
+obj/market.o: market.cpp            $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
-obj/ui.o: ui.cpp                    $(HEADERS) net.h uibase.h ui.h market.h\r
+obj/ui.o: ui.cpp                    $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
 obj/uibase.o: uibase.cpp            uibase.h\r
@@ -75,11 +75,13 @@ obj/sha.o: sha.cpp                  sha.h
 obj/irc.o: irc.cpp                  $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
+obj/rpc.o: rpc.cpp                  $(HEADERS)\r
+       g++ -c $(CFLAGS) -o $@ $<\r
 \r
 \r
 \r
 OBJS=obj/util.o obj/script.o obj/db.o obj/net.o obj/main.o obj/market.o \\r
-        obj/ui.o obj/uibase.o obj/sha.o obj/irc.o\r
+        obj/ui.o obj/uibase.o obj/sha.o obj/irc.o obj/rpc.o\r
 \r
 bitcoin: headers.h.gch $(OBJS)\r
        g++ $(CFLAGS) -o $@ $(LIBPATHS) $(OBJS) $(LIBS)\r
index 81dcbd7..8defcbb 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright (c) 2009 Satoshi Nakamoto\r
+# Copyright (c) 2009-2010 Satoshi Nakamoto\r
 # Distributed under the MIT/X11 software license, see the accompanying\r
 # file license.txt or http://www.opensource.org/licenses/mit-license.php.\r
 \r
@@ -35,14 +35,14 @@ LIBS= \
 \r
 WXDEFS=-D__WXGTK__ -DNOPCH\r
 CFLAGS=-O0 -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(WXDEFS) $(INCLUDEPATHS)\r
-HEADERS=headers.h util.h main.h serialize.h uint256.h key.h bignum.h script.h db.h base58.h\r
+HEADERS=headers.h strlcpy.h serialize.h uint256.h util.h key.h bignum.h base58.h script.h db.h net.h irc.h main.h market.h rpc.h uibase.h ui.h\r
 \r
 \r
 \r
 all: bitcoin\r
 \r
 \r
-headers.h.gch: headers.h $(HEADERS) net.h irc.h market.h uibase.h ui.h\r
+headers.h.gch: headers.h            $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
 obj/util.o: util.cpp                $(HEADERS)\r
@@ -51,19 +51,19 @@ obj/util.o: util.cpp                $(HEADERS)
 obj/script.o: script.cpp            $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
-obj/db.o: db.cpp                    $(HEADERS) market.h\r
+obj/db.o: db.cpp                    $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
-obj/net.o: net.cpp                  $(HEADERS) net.h\r
+obj/net.o: net.cpp                  $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
-obj/main.o: main.cpp                $(HEADERS) net.h market.h sha.h\r
+obj/main.o: main.cpp                $(HEADERS) sha.h\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
-obj/market.o: market.cpp            $(HEADERS) market.h\r
+obj/market.o: market.cpp            $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
-obj/ui.o: ui.cpp                    $(HEADERS) net.h uibase.h ui.h market.h\r
+obj/ui.o: ui.cpp                    $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
 obj/uibase.o: uibase.cpp            uibase.h\r
@@ -75,11 +75,13 @@ obj/sha.o: sha.cpp                  sha.h
 obj/irc.o: irc.cpp                  $(HEADERS)\r
        g++ -c $(CFLAGS) -o $@ $<\r
 \r
+obj/rpc.o: rpc.cpp                  $(HEADERS)\r
+       g++ -c $(CFLAGS) -o $@ $<\r
 \r
 \r
 \r
 OBJS=obj/util.o obj/script.o obj/db.o obj/net.o obj/main.o obj/market.o \\r
-        obj/ui.o obj/uibase.o obj/sha.o obj/irc.o\r
+        obj/ui.o obj/uibase.o obj/sha.o obj/irc.o obj/rpc.o\r
 \r
 bitcoin: headers.h.gch $(OBJS)\r
        g++ $(CFLAGS) -o $@ $(LIBPATHS) $(OBJS) $(LIBS)\r
index fb7f308..73fd1cf 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright (c) 2009 Satoshi Nakamoto\r
+# Copyright (c) 2009-2010 Satoshi Nakamoto\r
 # Distributed under the MIT/X11 software license, see the accompanying\r
 # file license.txt or http://www.opensource.org/licenses/mit-license.php.\r
 \r
@@ -14,15 +14,16 @@ DEBUGFLAGS=/Zi /Od /D__WXDEBUG__
 \r
 \r
 INCLUDEPATHS=/I"/boost" /I"/db/build_windows" /I"/openssl/include" /I"/wxwidgets/lib/vc_lib/mswd" /I"/wxwidgets/include"\r
-LIBPATHS=/LIBPATH:"/db/build_windows/$(BUILD)" /LIBPATH:"/openssl/out" /LIBPATH:"/wxwidgets/lib/vc_lib"\r
+LIBPATHS=/LIBPATH:"/boost/stage/lib" /LIBPATH:"/db/build_windows/$(BUILD)" /LIBPATH:"/openssl/out" /LIBPATH:"/wxwidgets/lib/vc_lib"\r
 LIBS= \\r
+    libboost_system-vc80-mt-gd.lib libboost_filesystem-vc80-mt-gd.lib \\r
     libdb47s$(D).lib \\r
     libeay32.lib \\r
     wxmsw28$(D)_richtext.lib wxmsw28$(D)_html.lib wxmsw28$(D)_core.lib wxmsw28$(D)_adv.lib wxbase28$(D).lib wxtiff$(D).lib wxjpeg$(D).lib wxpng$(D).lib wxzlib$(D).lib wxregex$(D).lib wxexpat$(D).lib \\r
     kernel32.lib user32.lib gdi32.lib comdlg32.lib winspool.lib winmm.lib shell32.lib comctl32.lib ole32.lib oleaut32.lib uuid.lib rpcrt4.lib advapi32.lib ws2_32.lib shlwapi.lib\r
 WXDEFS=/DWIN32 /D__WXMSW__ /D_WINDOWS /DNOPCH\r
 CFLAGS=/c /nologo /Ob0 /MD$(D) /EHsc /GR /Zm300 /YX /Fpobj/headers.pch $(DEBUGFLAGS) $(WXDEFS) $(INCLUDEPATHS)\r
-HEADERS=headers.h util.h main.h serialize.h uint256.h key.h bignum.h script.h db.h base58.h\r
+HEADERS=headers.h strlcpy.h serialize.h uint256.h util.h key.h bignum.h base58.h script.h db.h net.h irc.h main.h market.h rpc.h uibase.h ui.h\r
 \r
 \r
 \r
@@ -35,37 +36,41 @@ obj\util.obj: util.cpp        $(HEADERS)
 obj\script.obj: script.cpp    $(HEADERS)\r
     cl $(CFLAGS) /Fo$@ %s\r
 \r
-obj\db.obj: db.cpp            $(HEADERS) market.h\r
+obj\db.obj: db.cpp            $(HEADERS)\r
     cl $(CFLAGS) /Fo$@ %s\r
 \r
-obj\net.obj: net.cpp          $(HEADERS) net.h\r
+obj\net.obj: net.cpp          $(HEADERS)\r
     cl $(CFLAGS) /Fo$@ %s\r
 \r
-obj\main.obj: main.cpp        $(HEADERS) net.h market.h\r
+obj\main.obj: main.cpp        $(HEADERS) sha.h\r
     cl $(CFLAGS) /Fo$@ %s\r
 \r
-obj\market.obj: market.cpp    $(HEADERS) market.h\r
+obj\market.obj: market.cpp    $(HEADERS)\r
     cl $(CFLAGS) /Fo$@ %s\r
 \r
-obj\ui.obj: ui.cpp            $(HEADERS) net.h uibase.h ui.h market.h\r
+obj\ui.obj: ui.cpp            $(HEADERS)\r
     cl $(CFLAGS) /Fo$@ %s\r
 \r
 obj\uibase.obj: uibase.cpp    uibase.h\r
     cl $(CFLAGS) /Fo$@ %s\r
 \r
-obj\sha.obj: sha.cpp sha.h\r
+obj\sha.obj: sha.cpp          sha.h\r
     cl $(CFLAGS) /O2 /Fo$@ %s\r
 \r
 obj\irc.obj:  irc.cpp         $(HEADERS)\r
     cl $(CFLAGS) /Fo$@ %s\r
 \r
+obj\rpc.obj:  rpc.cpp         $(HEADERS)\r
+    cl $(CFLAGS) /Fo$@ %s\r
+\r
 obj\ui.res: ui.rc  rc/bitcoin.ico rc/check.ico rc/send16.bmp rc/send16mask.bmp rc/send16masknoshadow.bmp rc/send20.bmp rc/send20mask.bmp rc/addressbook16.bmp rc/addressbook16mask.bmp rc/addressbook20.bmp rc/addressbook20mask.bmp\r
     rc $(INCLUDEPATHS) $(WXDEFS) /Fo$@ %s\r
 \r
 \r
 \r
 OBJS=obj\util.obj obj\script.obj obj\db.obj obj\net.obj obj\main.obj obj\market.obj \\r
-  obj\ui.obj obj\uibase.obj obj\sha.obj obj\irc.obj obj\ui.res\r
+    obj\ui.obj obj\uibase.obj obj\sha.obj obj\irc.obj obj\rpc.obj \\r
+    obj\ui.res\r
 \r
 bitcoin.exe: $(OBJS)\r
     -kill /f bitcoin.exe & sleep 1\r
diff --git a/net.cpp b/net.cpp
index 38d05de..ada78eb 100644 (file)
--- a/net.cpp
+++ b/net.cpp
@@ -1,4 +1,4 @@
-// Copyright (c) 2009 Satoshi Nakamoto\r
+// Copyright (c) 2009-2010 Satoshi Nakamoto\r
 // Distributed under the MIT/X11 software license, see the accompanying\r
 // file license.txt or http://www.opensource.org/licenses/mit-license.php.\r
 \r
@@ -522,7 +522,6 @@ void CNode::Cleanup()
 void ThreadSocketHandler(void* parg)\r
 {\r
     IMPLEMENT_RANDOMIZE_STACK(ThreadSocketHandler(parg));\r
-\r
     try\r
     {\r
         vnThreadsRunning[0]++;\r
@@ -536,7 +535,6 @@ void ThreadSocketHandler(void* parg)
         vnThreadsRunning[0]--;\r
         throw; // support pthread_cancel()\r
     }\r
-\r
     printf("ThreadSocketHandler exiting\n");\r
 }\r
 \r
@@ -816,7 +814,6 @@ void ThreadSocketHandler2(void* parg)
 void ThreadOpenConnections(void* parg)\r
 {\r
     IMPLEMENT_RANDOMIZE_STACK(ThreadOpenConnections(parg));\r
-\r
     try\r
     {\r
         vnThreadsRunning[1]++;\r
@@ -830,7 +827,6 @@ void ThreadOpenConnections(void* parg)
         vnThreadsRunning[1]--;\r
         PrintException(NULL, "ThreadOpenConnections()");\r
     }\r
-\r
     printf("ThreadOpenConnections exiting\n");\r
 }\r
 \r
@@ -928,7 +924,7 @@ void ThreadOpenConnections2(void* parg)
                 //   30 days   27 hours\r
                 //   90 days   46 hours\r
                 //  365 days   93 hours\r
-                int64 nDelay = (int64)(3600.0 * sqrt(fabs(nSinceLastSeen) / 3600.0) + nRandomizer);\r
+                int64 nDelay = (int64)(3600.0 * sqrt(fabs((double)nSinceLastSeen) / 3600.0) + nRandomizer);\r
 \r
                 // Fast reconnect for one hour after last seen\r
                 if (nSinceLastSeen < 60 * 60)\r
@@ -1016,7 +1012,6 @@ bool OpenNetworkConnection(const CAddress& addrConnect)
 void ThreadMessageHandler(void* parg)\r
 {\r
     IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg));\r
-\r
     try\r
     {\r
         vnThreadsRunning[2]++;\r
@@ -1030,7 +1025,6 @@ void ThreadMessageHandler(void* parg)
         vnThreadsRunning[2]--;\r
         PrintException(NULL, "ThreadMessageHandler()");\r
     }\r
-\r
     printf("ThreadMessageHandler exiting\n");\r
 }\r
 \r
@@ -1329,7 +1323,7 @@ bool StopNode()
     fShutdown = true;\r
     nTransactionsUpdated++;\r
     int64 nStart = GetTime();\r
-    while (vnThreadsRunning[0] > 0 || vnThreadsRunning[2] > 0 || vnThreadsRunning[3] > 0)\r
+    while (vnThreadsRunning[0] > 0 || vnThreadsRunning[2] > 0 || vnThreadsRunning[3] > 0 || vnThreadsRunning[4] > 0)\r
     {\r
         if (GetTime() - nStart > 20)\r
             break;\r
@@ -1339,7 +1333,8 @@ bool StopNode()
     if (vnThreadsRunning[1] > 0) printf("ThreadOpenConnections still running\n");\r
     if (vnThreadsRunning[2] > 0) printf("ThreadMessageHandler still running\n");\r
     if (vnThreadsRunning[3] > 0) printf("ThreadBitcoinMiner still running\n");\r
-    while (vnThreadsRunning[2] > 0)\r
+    if (vnThreadsRunning[4] > 0) printf("ThreadRPCServer still running\n");\r
+    while (vnThreadsRunning[2] > 0 || vnThreadsRunning[4] > 0)\r
         Sleep(20);\r
     Sleep(50);\r
 \r
diff --git a/net.h b/net.h
index ba4607a..ce6f772 100644 (file)
--- a/net.h
+++ b/net.h
@@ -1,4 +1,4 @@
-// Copyright (c) 2009 Satoshi Nakamoto\r
+// Copyright (c) 2009-2010 Satoshi Nakamoto\r
 // Distributed under the MIT/X11 software license, see the accompanying\r
 // file license.txt or http://www.opensource.org/licenses/mit-license.php.\r
 \r
@@ -518,6 +518,7 @@ public:
     vector<CInv> vInventoryToSend;\r
     CCriticalSection cs_inventory;\r
     multimap<int64, CInv> mapAskFor;\r
+    int64 nLastSentTxInv;\r
 \r
     // publish and subscription\r
     vector<char> vfSubscribe;\r
diff --git a/rpc.cpp b/rpc.cpp
new file mode 100644 (file)
index 0000000..9f28e7e
--- /dev/null
+++ b/rpc.cpp
@@ -0,0 +1,641 @@
+// Copyright (c) 2010 Satoshi Nakamoto\r
+// Distributed under the MIT/X11 software license, see the accompanying\r
+// file license.txt or http://www.opensource.org/licenses/mit-license.php.\r
+\r
+#include "headers.h"\r
+#undef printf\r
+#include <boost/asio.hpp>\r
+#include "json/json_spirit_reader_template.h"\r
+#include "json/json_spirit_writer_template.h"\r
+#include "json/json_spirit_utils.h"\r
+#define printf OutputDebugStringF\r
+// MinGW 3.4.5 gets "fatal error: had to relocate PCH" if the json headers are\r
+// precompiled in headers.h.  The problem might be when the pch file goes over\r
+// a certain size around 145MB.  If we need access to json_spirit outside this\r
+// file, we could use the compiled json_spirit option.\r
+\r
+using boost::asio::ip::tcp;\r
+using namespace json_spirit;\r
+\r
+void ThreadRPCServer2(void* parg);\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+///\r
+/// Note: I'm not finished designing this interface, it's still subject to change.\r
+///\r
+\r
+\r
+\r
+Value stop(const Array& params)\r
+{\r
+    if (params.size() != 0)\r
+        throw runtime_error(\r
+            "stop (no parameters)\n"\r
+            "Stop bitcoin server.");\r
+\r
+    // Shutdown will take long enough that the response should get back\r
+    CreateThread(Shutdown, NULL);\r
+    return "bitcoin server stopping";\r
+}\r
+\r
+\r
+Value getblockcount(const Array& params)\r
+{\r
+    if (params.size() != 0)\r
+        throw runtime_error(\r
+            "getblockcount (no parameters)\n"\r
+            "Returns the number of blocks in the longest block chain.");\r
+\r
+    return nBestHeight + 1;\r
+}\r
+\r
+\r
+Value getblocknumber(const Array& params)\r
+{\r
+    if (params.size() != 0)\r
+        throw runtime_error(\r
+            "getblocknumber (no parameters)\n"\r
+            "Returns the block number of the latest block in the longest block chain.");\r
+\r
+    return nBestHeight;\r
+}\r
+\r
+\r
+Value getdifficulty(const Array& params)\r
+{\r
+    if (params.size() != 0)\r
+        throw runtime_error(\r
+            "getdifficulty (no parameters)\n"\r
+            "Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");\r
+\r
+    if (pindexBest == NULL)\r
+        throw runtime_error("block chain not loaded");\r
+\r
+    // Floating point number that is a multiple of the minimum difficulty,\r
+    // minimum difficulty = 1.0.\r
+    int nShift = 256 - 32 - 31; // to fit in a uint\r
+    double dMinimum = (CBigNum().SetCompact(bnProofOfWorkLimit.GetCompact()) >> nShift).getuint();\r
+    double dCurrently = (CBigNum().SetCompact(pindexBest->nBits) >> nShift).getuint();\r
+    return dMinimum / dCurrently;\r
+}\r
+\r
+\r
+Value getnewaddress(const Array& params)\r
+{\r
+    if (params.size() > 1)\r
+        throw runtime_error(\r
+            "getnewaddress [label]\n"\r
+            "Returns a new bitcoin address for receiving payments.  "\r
+            "If [label] is specified (recommended), it is added to the address book "\r
+            "so payments received with the address will be labeled.");\r
+\r
+    // Parse the label first so we don't generate a key if there's an error\r
+    string strLabel;\r
+    if (params.size() > 0)\r
+        strLabel = params[0].get_str();\r
+\r
+    // Generate a new key that is added to wallet\r
+    string strAddress = PubKeyToAddress(GenerateNewKey());\r
+\r
+    if (params.size() > 0)\r
+        SetAddressBookName(strAddress, strLabel);\r
+    return strAddress;\r
+}\r
+\r
+\r
+Value sendtoaddress(const Array& params)\r
+{\r
+    if (params.size() < 2 || params.size() > 4)\r
+        throw runtime_error(\r
+            "sendtoaddress <bitcoinaddress> <amount> [comment] [comment-to]\n"\r
+            "<amount> is a real and is rounded to the nearest 0.01");\r
+\r
+    string strAddress = params[0].get_str();\r
+\r
+    // Amount\r
+    if (params[1].get_real() <= 0.0 || params[1].get_real() > 21000000.0)\r
+        throw runtime_error("Invalid amount");\r
+    int64 nAmount = roundint64(params[1].get_real() * 100.00) * CENT;\r
+\r
+    // Wallet comments\r
+    CWalletTx wtx;\r
+    if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())\r
+        wtx.mapValue["message"] = params[2].get_str();\r
+    if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())\r
+        wtx.mapValue["to"]      = params[3].get_str();\r
+\r
+    string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);\r
+    if (strError != "")\r
+        throw runtime_error(strError);\r
+    return "sent";\r
+}\r
+\r
+\r
+Value listtransactions(const Array& params)\r
+{\r
+    if (params.size() > 2)\r
+        throw runtime_error(\r
+            "listtransactions [count=10] [includegenerated=false]\n"\r
+            "Returns up to [count] most recent transactions.");\r
+\r
+    int64 nCount = 10;\r
+    if (params.size() > 0)\r
+        nCount = params[0].get_int64();\r
+    bool fGenerated = false;\r
+    if (params.size() > 1)\r
+        fGenerated = params[1].get_bool();\r
+\r
+    Array ret;\r
+    //// not finished\r
+    ret.push_back("not implemented yet");\r
+    return ret;\r
+}\r
+\r
+\r
+Value getamountpaid(const Array& params)\r
+{\r
+    if (params.size() < 1 || params.size() > 2)\r
+        throw runtime_error(\r
+            "getamountpaid <bitcoinaddress> [minconf=1]\n"\r
+            "Returns the total amount paid to <bitcoinaddress> in transactions with at least [minconf] confirmations.");\r
+\r
+    // Bitcoin address\r
+    string strAddress = params[0].get_str();\r
+    CScript scriptPubKey;\r
+    if (!scriptPubKey.SetBitcoinAddress(strAddress))\r
+        throw runtime_error("Invalid bitcoin address");\r
+\r
+    // Minimum confirmations\r
+    int nMinDepth = 1;\r
+    if (params.size() > 1)\r
+        nMinDepth = params[1].get_int();\r
+\r
+    // Tally\r
+    int64 nAmount = 0;\r
+    CRITICAL_BLOCK(cs_mapWallet)\r
+    {\r
+        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)\r
+        {\r
+            const CWalletTx& wtx = (*it).second;\r
+            if (wtx.IsCoinBase() || !wtx.IsFinal())\r
+                continue;\r
+\r
+            foreach(const CTxOut& txout, wtx.vout)\r
+                if (txout.scriptPubKey == scriptPubKey)\r
+                    if (wtx.GetDepthInMainChain() >= nMinDepth)\r
+                        nAmount += txout.nValue;\r
+        }\r
+    }\r
+\r
+    return (double)nAmount / (double)COIN;\r
+}\r
+\r
+\r
+struct tallyitem\r
+{\r
+    int64 nAmount;\r
+    int nConf;\r
+    tallyitem()\r
+    {\r
+        nAmount = 0;\r
+        nConf = INT_MAX;\r
+    }\r
+};\r
+\r
+Value getallpayments(const Array& params)\r
+{\r
+    if (params.size() > 1)\r
+        throw runtime_error(\r
+            "getallpayments [minconf=1]\n"\r
+            "[minconf] is the minimum number of confirmations before payments are included.\n"\r
+            "Returns an array of objects containing:\n"\r
+            "  \"address\" : bitcoin address\n"\r
+            "  \"amount\" : total amount paid to the address\n"\r
+            "  \"conf\" : number of confirmations\n"\r
+            "  \"label\" : the label set for this address when it was created by getnewaddress");\r
+\r
+    // Minimum confirmations\r
+    int nMinDepth = 1;\r
+    if (params.size() > 0)\r
+        nMinDepth = params[0].get_int();\r
+\r
+    // Tally\r
+    map<uint160, tallyitem> mapTally;\r
+    CRITICAL_BLOCK(cs_mapWallet)\r
+    {\r
+        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)\r
+        {\r
+            const CWalletTx& wtx = (*it).second;\r
+            if (wtx.IsCoinBase() || !wtx.IsFinal())\r
+                continue;\r
+\r
+            int nDepth = wtx.GetDepthInMainChain();\r
+            if (nDepth >= nMinDepth)\r
+            {\r
+                foreach(const CTxOut& txout, wtx.vout)\r
+                {\r
+                    uint160 hash160 = txout.scriptPubKey.GetBitcoinAddressHash160();\r
+                    if (hash160 == 0 || !mapPubKeys.count(hash160))\r
+                        continue;\r
+\r
+                    tallyitem& item = mapTally[hash160];\r
+                    item.nAmount += txout.nValue;\r
+                    item.nConf = min(item.nConf, nDepth);\r
+                }\r
+            }\r
+        }\r
+    }\r
+\r
+    // Reply\r
+    Array ret;\r
+    CRITICAL_BLOCK(cs_mapAddressBook)\r
+    {\r
+        for (map<uint160, tallyitem>::iterator it = mapTally.begin(); it != mapTally.end(); ++it)\r
+        {\r
+            string strAddress = Hash160ToAddress((*it).first);\r
+            string strLabel;\r
+            map<string, string>::iterator mi = mapAddressBook.find(strAddress);\r
+            if (mi != mapAddressBook.end())\r
+                strLabel = (*mi).second;\r
+\r
+            Object obj;\r
+            obj.push_back(Pair("address", strAddress));\r
+            obj.push_back(Pair("amount",  (double)(*it).second.nAmount / (double)COIN));\r
+            obj.push_back(Pair("conf",    (*it).second.nConf));\r
+            obj.push_back(Pair("label",   strLabel));\r
+            ret.push_back(obj);\r
+        }\r
+    }\r
+    return ret;\r
+}\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+//\r
+// Call Table\r
+//\r
+\r
+typedef Value(*rpcfn_type)(const Array& params);\r
+pair<string, rpcfn_type> pCallTable[] =\r
+{\r
+    make_pair("stop",               &stop),\r
+    make_pair("getblockcount",      &getblockcount),\r
+    make_pair("getblocknumber",     &getblocknumber),\r
+    make_pair("getdifficulty",      &getdifficulty),\r
+    make_pair("getnewaddress",      &getnewaddress),\r
+    make_pair("sendtoaddress",      &sendtoaddress),\r
+    make_pair("listtransactions",   &listtransactions),\r
+    make_pair("getamountpaid",      &getamountpaid),\r
+    make_pair("getallpayments",     &getallpayments),\r
+};\r
+map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));\r
+\r
+\r
+\r
+\r
+//\r
+// HTTP protocol\r
+//\r
+// This ain't Apache.  We're just using HTTP header for the length field\r
+// and to be compatible with other JSON-RPC implementations.\r
+//\r
+\r
+string HTTPPost(const string& strMsg)\r
+{\r
+    return strprintf(\r
+            "POST / HTTP/1.1\r\n"\r
+            "User-Agent: json-rpc/1.0\r\n"\r
+            "Host: 127.0.0.1\r\n"\r
+            "Content-Type: application/json\r\n"\r
+            "Content-Length: %d\r\n"\r
+            "Accept: application/json\r\n"\r
+            "\r\n"\r
+            "%s",\r
+        strMsg.size(),\r
+        strMsg.c_str());\r
+}\r
+\r
+string HTTPReply(const string& strMsg, int nStatus=200)\r
+{\r
+    string strStatus;\r
+    if (nStatus == 200) strStatus = "OK";\r
+    if (nStatus == 500) strStatus = "Internal Server Error";\r
+    return strprintf(\r
+            "HTTP/1.1 %d %s\r\n"\r
+            "Connection: close\r\n"\r
+            "Content-Length: %d\r\n"\r
+            "Content-Type: application/json\r\n"\r
+            "Date: Sat, 08 Jul 2006 12:04:08 GMT\r\n"\r
+            "Server: json-rpc/1.0\r\n"\r
+            "\r\n"\r
+            "%s",\r
+        nStatus,\r
+        strStatus.c_str(),\r
+        strMsg.size(),\r
+        strMsg.c_str());\r
+}\r
+\r
+int ReadHTTPHeader(tcp::iostream& stream)\r
+{\r
+    int nLen = 0;\r
+    loop\r
+    {\r
+        string str;\r
+        std::getline(stream, str);\r
+        if (str.empty() || str == "\r")\r
+            break;\r
+        if (str.substr(0,15) == "Content-Length:")\r
+            nLen = atoi(str.substr(15));\r
+    }\r
+    return nLen;\r
+}\r
+\r
+inline string ReadHTTP(tcp::iostream& stream)\r
+{\r
+    // Read header\r
+    int nLen = ReadHTTPHeader(stream);\r
+    if (nLen <= 0)\r
+        return string();\r
+\r
+    // Read message\r
+    vector<char> vch(nLen);\r
+    stream.read(&vch[0], nLen);\r
+    return string(vch.begin(), vch.end());\r
+}\r
+\r
+\r
+\r
+//\r
+// JSON-RPC protocol\r
+//\r
+// http://json-rpc.org/wiki/specification\r
+// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx\r
+//\r
+\r
+string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)\r
+{\r
+    Object request;\r
+    request.push_back(Pair("method", strMethod));\r
+    request.push_back(Pair("params", params));\r
+    request.push_back(Pair("id", id));\r
+    return write_string(Value(request), false) + "\n";\r
+}\r
+\r
+string JSONRPCReply(const Value& result, const Value& error, const Value& id)\r
+{\r
+    Object reply;\r
+    if (error.type() != null_type)\r
+        reply.push_back(Pair("result", Value::null));\r
+    else\r
+        reply.push_back(Pair("result", result));\r
+    reply.push_back(Pair("error", error));\r
+    reply.push_back(Pair("id", id));\r
+    return write_string(Value(reply), false) + "\n";\r
+}\r
+\r
+\r
+\r
+\r
+void ThreadRPCServer(void* parg)\r
+{\r
+    IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));\r
+    try\r
+    {\r
+        vnThreadsRunning[4]++;\r
+        ThreadRPCServer2(parg);\r
+        vnThreadsRunning[4]--;\r
+    }\r
+    catch (std::exception& e) {\r
+        vnThreadsRunning[4]--;\r
+        PrintException(&e, "ThreadRPCServer()");\r
+    } catch (...) {\r
+        vnThreadsRunning[4]--;\r
+        PrintException(NULL, "ThreadRPCServer()");\r
+    }\r
+    printf("ThreadRPCServer exiting\n");\r
+}\r
+\r
+void ThreadRPCServer2(void* parg)\r
+{\r
+    printf("ThreadRPCServer started\n");\r
+\r
+    // Bind to loopback 127.0.0.1 so the socket can only be accessed locally\r
+    boost::asio::io_service io_service;\r
+    tcp::endpoint endpoint(boost::asio::ip::address_v4::loopback(), 8332);\r
+    tcp::acceptor acceptor(io_service, endpoint);\r
+\r
+    loop\r
+    {\r
+        // Accept connection\r
+        tcp::iostream stream;\r
+        tcp::endpoint peer;\r
+        vnThreadsRunning[4]--;\r
+        acceptor.accept(*stream.rdbuf(), peer);\r
+        vnThreadsRunning[4]++;\r
+        if (fShutdown)\r
+            return;\r
+\r
+        // Shouldn't be possible for anyone else to connect, but just in case\r
+        if (peer.address().to_string() != "127.0.0.1")\r
+            continue;\r
+\r
+        // Receive request\r
+        string strRequest = ReadHTTP(stream);\r
+        printf("ThreadRPCServer request=%s", strRequest.c_str());\r
+\r
+        // Handle multiple invocations per request\r
+        string::iterator begin = strRequest.begin();\r
+        while (skipspaces(begin), begin != strRequest.end())\r
+        {\r
+            string::iterator prev = begin;\r
+            Value id;\r
+            try\r
+            {\r
+                // Parse request\r
+                Value valRequest;\r
+                if (!read_range(begin, strRequest.end(), valRequest))\r
+                    throw runtime_error("Parse error.");\r
+                const Object& request = valRequest.get_obj();\r
+                if (find_value(request, "method").type() != str_type ||\r
+                    find_value(request, "params").type() != array_type)\r
+                    throw runtime_error("Invalid request.");\r
+\r
+                string strMethod    = find_value(request, "method").get_str();\r
+                const Array& params = find_value(request, "params").get_array();\r
+                id                  = find_value(request, "id");\r
+\r
+                // Execute\r
+                map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);\r
+                if (mi == mapCallTable.end())\r
+                    throw runtime_error("Method not found.");\r
+                Value result = (*(*mi).second)(params);\r
+\r
+                // Send reply\r
+                string strReply = JSONRPCReply(result, Value::null, id);\r
+                stream << HTTPReply(strReply, 200) << std::flush;\r
+            }\r
+            catch (std::exception& e)\r
+            {\r
+                // Send error reply\r
+                string strReply = JSONRPCReply(Value::null, e.what(), id);\r
+                stream << HTTPReply(strReply, 500) << std::flush;\r
+            }\r
+            if (begin == prev)\r
+                break;\r
+        }\r
+    }\r
+}\r
+\r
+\r
+\r
+\r
+Value CallRPC(const string& strMethod, const Array& params)\r
+{\r
+    // Connect to localhost\r
+    tcp::iostream stream("127.0.0.1", "8332");\r
+    if (stream.fail())\r
+        throw runtime_error("unable to connect to server");\r
+\r
+    // Send request\r
+    string strRequest = JSONRPCRequest(strMethod, params, 1);\r
+    stream << HTTPPost(strRequest) << std::flush;\r
+\r
+    // Receive reply\r
+    string strReply = ReadHTTP(stream);\r
+    if (strReply.empty())\r
+        throw runtime_error("no response from server");\r
+\r
+    // Parse reply\r
+    Value valReply;\r
+    if (!read_string(strReply, valReply))\r
+        throw runtime_error("couldn't parse reply from server");\r
+    const Object& reply = valReply.get_obj();\r
+    if (reply.empty())\r
+        throw runtime_error("expected reply to have result, error and id properties");\r
+\r
+    const Value& result = find_value(reply, "result");\r
+    const Value& error  = find_value(reply, "error");\r
+    const Value& id     = find_value(reply, "id");\r
+\r
+    if (error.type() == str_type)\r
+        throw runtime_error(error.get_str());\r
+    else if (error.type() != null_type)\r
+        throw runtime_error(write_string(error, false));\r
+    return result;\r
+}\r
+\r
+\r
+\r
+\r
+template<typename T>\r
+void ConvertTo(Value& value)\r
+{\r
+    if (value.type() == str_type)\r
+    {\r
+        // reinterpret string as unquoted json value\r
+        Value value2;\r
+        if (!read_string(value.get_str(), value2))\r
+            throw runtime_error("type mismatch");\r
+        value = value2.get_value<T>();\r
+    }\r
+    else\r
+    {\r
+        value = value.get_value<T>();\r
+    }\r
+}\r
+\r
+int CommandLineRPC(int argc, char *argv[])\r
+{\r
+    try\r
+    {\r
+        // Check that method exists\r
+        if (argc < 2)\r
+            throw runtime_error("too few parameters");\r
+        string strMethod = argv[1];\r
+        if (!mapCallTable.count(strMethod))\r
+            throw runtime_error(strprintf("unknown command: %s", strMethod.c_str()));\r
+\r
+        // Parameters default to strings\r
+        Array params;\r
+        for (int i = 2; i < argc; i++)\r
+            params.push_back(argv[i]);\r
+\r
+        // Special case other types\r
+        int n = params.size();\r
+        if (strMethod == "sendtoaddress"    && n > 1) ConvertTo<double>(params[1]);\r
+        if (strMethod == "listtransactions" && n > 0) ConvertTo<boost::int64_t>(params[0]);\r
+        if (strMethod == "listtransactions" && n > 1) ConvertTo<bool>(params[1]);\r
+        if (strMethod == "getamountpaid"    && n > 1) ConvertTo<boost::int64_t>(params[1]);\r
+        if (strMethod == "getallpayments"   && n > 0) ConvertTo<boost::int64_t>(params[0]);\r
+\r
+        // Execute\r
+        Value result = CallRPC(strMethod, params);\r
+\r
+        // Print result\r
+        string strResult = (result.type() == str_type ? result.get_str() : write_string(result, true));\r
+        if (result.type() != null_type)\r
+        {\r
+            if (fWindows)\r
+                // Windows GUI apps can't print to command line,\r
+                // so for now settle for a message box yuck\r
+                wxMessageBox(strResult.c_str(), "Bitcoin", wxOK);\r
+            else\r
+                fprintf(stdout, "%s\n", strResult.c_str());\r
+        }\r
+        return 0;\r
+    }\r
+    catch (std::exception& e) {\r
+        if (fWindows)\r
+            wxMessageBox(strprintf("error: %s\n", e.what()).c_str(), "Bitcoin", wxOK);\r
+        else\r
+            fprintf(stderr, "error: %s\n", e.what());\r
+    } catch (...) {\r
+        PrintException(NULL, "CommandLineRPC()");\r
+    }\r
+    return 1;\r
+}\r
+\r
+\r
+\r
+\r
+#ifdef TEST\r
+int main(int argc, char *argv[])\r
+{\r
+#ifdef _MSC_VER\r
+    // Turn off microsoft heap dump noise\r
+    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);\r
+    _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));\r
+#endif\r
+    setbuf(stdin, NULL);\r
+    setbuf(stdout, NULL);\r
+    setbuf(stderr, NULL);\r
+\r
+    try\r
+    {\r
+        if (argc >= 2 && string(argv[1]) == "-server")\r
+        {\r
+            printf("server ready\n");\r
+            ThreadRPCServer(NULL);\r
+        }\r
+        else\r
+        {\r
+            return CommandLineRPC(argc, argv);\r
+        }\r
+    }\r
+    catch (std::exception& e) {\r
+        PrintException(&e, "main()");\r
+    } catch (...) {\r
+        PrintException(NULL, "main()");\r
+    }\r
+    return 0;\r
+}\r
+#endif\r
diff --git a/rpc.h b/rpc.h
new file mode 100644 (file)
index 0000000..81ad840
--- /dev/null
+++ b/rpc.h
@@ -0,0 +1,6 @@
+// Copyright (c) 2010 Satoshi Nakamoto\r
+// Distributed under the MIT/X11 software license, see the accompanying\r
+// file license.txt or http://www.opensource.org/licenses/mit-license.php.\r
+\r
+void ThreadRPCServer(void* parg);\r
+int CommandLineRPC(int argc, char *argv[]);\r
index a41de2a..98f5afd 100644 (file)
@@ -660,7 +660,7 @@ bool EvalScript(const CScript& script, const CTransaction& txTo, unsigned int nI
                 if (stack.size() < 1)\r
                     return false;\r
                 valtype& vch = stacktop(-1);\r
-                valtype vchHash(opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160 ? 20 : 32);\r
+                valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);\r
                 if (opcode == OP_RIPEMD160)\r
                     RIPEMD160(&vch[0], vch.size(), &vchHash[0]);\r
                 else if (opcode == OP_SHA1)\r
@@ -753,9 +753,9 @@ bool EvalScript(const CScript& script, const CTransaction& txTo, unsigned int nI
                 CScript scriptCode(pbegincodehash, pend);\r
 \r
                 // Drop the signatures, since there's no way for a signature to sign itself\r
-                for (int i = 0; i < nSigsCount; i++)\r
+                for (int k = 0; k < nSigsCount; k++)\r
                 {\r
-                    valtype& vchSig = stacktop(-isig-i);\r
+                    valtype& vchSig = stacktop(-isig-k);\r
                     scriptCode.FindAndDelete(CScript(vchSig));\r
                 }\r
 \r
@@ -909,7 +909,6 @@ bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CSc
 \r
 \r
 \r
-\r
 bool Solver(const CScript& scriptPubKey, vector<pair<opcodetype, valtype> >& vSolutionRet)\r
 {\r
     // Templates\r
@@ -919,7 +918,7 @@ bool Solver(const CScript& scriptPubKey, vector<pair<opcodetype, valtype> >& vSo
         // Standard tx, sender provides pubkey, receiver adds signature\r
         vTemplates.push_back(CScript() << OP_PUBKEY << OP_CHECKSIG);\r
 \r
-        // Short account number tx, sender provides hash of pubkey, receiver provides signature and pubkey\r
+        // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey\r
         vTemplates.push_back(CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG);\r
     }\r
 \r
index 0d97773..9e41889 100644 (file)
--- a/script.h
+++ b/script.h
@@ -1,4 +1,4 @@
-// Copyright (c) 2009 Satoshi Nakamoto\r
+// Copyright (c) 2009-2010 Satoshi Nakamoto\r
 // Distributed under the MIT/X11 software license, see the accompanying\r
 // file license.txt or http://www.opensource.org/licenses/mit-license.php.\r
 \r
@@ -472,7 +472,7 @@ public:
 \r
     bool GetOp(iterator& pc, opcodetype& opcodeRet, vector<unsigned char>& vchRet)\r
     {\r
-         // This is why people hate C++\r
+         // Wrapper so it can be called with either iterator or const_iterator\r
          const_iterator pc2 = pc;\r
          bool fRet = GetOp(pc2, opcodeRet, vchRet);\r
          pc = begin() + (pc2 - begin());\r
@@ -551,6 +551,46 @@ public:
     }\r
 \r
 \r
+    uint160 GetBitcoinAddressHash160() const\r
+    {\r
+        opcodetype opcode;\r
+        vector<unsigned char> vch;\r
+        CScript::const_iterator pc = begin();\r
+        if (!GetOp(pc, opcode, vch) || opcode != OP_DUP) return 0;\r
+        if (!GetOp(pc, opcode, vch) || opcode != OP_HASH160) return 0;\r
+        if (!GetOp(pc, opcode, vch) || vch.size() != sizeof(uint160)) return 0;\r
+        uint160 hash160 = uint160(vch);\r
+        if (!GetOp(pc, opcode, vch) || opcode != OP_EQUALVERIFY) return 0;\r
+        if (!GetOp(pc, opcode, vch) || opcode != OP_CHECKSIG) return 0;\r
+        if (pc != end()) return 0;\r
+        return hash160;\r
+    }\r
+\r
+    string GetBitcoinAddress() const\r
+    {\r
+        uint160 hash160 = GetBitcoinAddressHash160();\r
+        if (hash160 == 0)\r
+            return "";\r
+        return Hash160ToAddress(hash160);\r
+    }\r
+\r
+    void SetBitcoinAddress(const uint160& hash160)\r
+    {\r
+        this->clear();\r
+        *this << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;\r
+    }\r
+\r
+    bool SetBitcoinAddress(const string& strAddress)\r
+    {\r
+        this->clear();\r
+        uint160 hash160;\r
+        if (!AddressToHash160(strAddress, hash160))\r
+            return false;\r
+        SetBitcoinAddress(hash160);\r
+        return true;\r
+    }\r
+\r
+\r
     void PrintHex() const\r
     {\r
         printf("CScript(%s)\n", HexStr(begin(), end()).c_str());\r
index 439ef64..eb090ae 100644 (file)
@@ -19,8 +19,8 @@ class CScript;
 class CDataStream;\r
 class CAutoFile;\r
 \r
-static const int VERSION = 200;\r
-static const char* pszSubVer = " test2";\r
+static const int VERSION = 201;\r
+static const char* pszSubVer = ".0";\r
 \r
 \r
 \r
diff --git a/ui.cpp b/ui.cpp
index 5d93ad2..586200d 100644 (file)
--- a/ui.cpp
+++ b/ui.cpp
@@ -21,7 +21,6 @@ DEFINE_EVENT_TYPE(wxEVT_REPLY3)
 \r
 CMainFrame* pframeMain = NULL;\r
 CMyTaskBarIcon* ptaskbaricon = NULL;\r
-map<string, string> mapAddressBook;\r
 bool fRandSendTest = false;\r
 void RandSend();\r
 extern int g_isPainting;\r
@@ -177,8 +176,11 @@ void CalledMessageBox(const string& message, const string& caption, int style, w
 \r
 int ThreadSafeMessageBox(const string& message, const string& caption, int style, wxWindow* parent, int x, int y)\r
 {\r
-    if (mapArgs.count("-noui"))\r
+    if (fDaemon)\r
+    {\r
+        printf("wxMessageBox %s: %s\n", caption.c_str(), message.c_str());\r
         return wxOK;\r
+    }\r
 \r
 #ifdef __WXMSW__\r
     return wxMessageBox(message, caption, style, parent, x, y);\r
@@ -413,7 +415,7 @@ void Shutdown(void* parg)
         StopNode();\r
         DBFlush(true);\r
         CreateThread(ExitTimeout, NULL);\r
-        Sleep(10);\r
+        Sleep(50);\r
         printf("Bitcoin exiting\n\n");\r
         fExit = true;\r
         exit(0);\r
@@ -697,19 +699,22 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)
                     vector<unsigned char> vchPubKey;\r
                     if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))\r
                     {\r
-                        string strAddress = PubKeyToAddress(vchPubKey);\r
-                        if (mapAddressBook.count(strAddress))\r
+                        CRITICAL_BLOCK(cs_mapAddressBook)\r
                         {\r
-                            //strDescription += "Received payment to ";\r
-                            //strDescription += "Received with address ";\r
-                            strDescription += "From: unknown, To: ";\r
-                            strDescription += strAddress;\r
-                            /// The labeling feature is just too confusing, so I hid it\r
-                            /// by putting it at the end where it runs off the screen.\r
-                            /// It can still be seen by widening the column, or in the\r
-                            /// details dialog.\r
-                            if (!mapAddressBook[strAddress].empty())\r
-                                strDescription += " (" + mapAddressBook[strAddress] + ")";\r
+                            string strAddress = PubKeyToAddress(vchPubKey);\r
+                            if (mapAddressBook.count(strAddress))\r
+                            {\r
+                                //strDescription += "Received payment to ";\r
+                                //strDescription += "Received with address ";\r
+                                strDescription += "From: unknown, To: ";\r
+                                strDescription += strAddress;\r
+                                /// The labeling feature is just too confusing, so I hid it\r
+                                /// by putting it at the end where it runs off the screen.\r
+                                /// It can still be seen by widening the column, or in the\r
+                                /// details dialog.\r
+                                if (!mapAddressBook[strAddress].empty())\r
+                                    strDescription += " (" + mapAddressBook[strAddress] + ")";\r
+                            }\r
                         }\r
                     }\r
                     break;\r
@@ -776,8 +781,9 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)
                 }\r
 \r
                 string strDescription = "To: ";\r
-                if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())\r
-                    strDescription += mapAddressBook[strAddress] + " ";\r
+                CRITICAL_BLOCK(cs_mapAddressBook)\r
+                    if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())\r
+                        strDescription += mapAddressBook[strAddress] + " ";\r
                 strDescription += strAddress;\r
                 if (!mapValue["message"].empty())\r
                 {\r
@@ -1273,238 +1279,241 @@ void CMainFrame::OnListItemActivatedOrdersReceived(wxListEvent& event)
 \r
 CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetailsDialogBase(parent)\r
 {\r
-    string strHTML;\r
-    strHTML.reserve(4000);\r
-    strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";\r
+    CRITICAL_BLOCK(cs_mapAddressBook)\r
+    {\r
+        string strHTML;\r
+        strHTML.reserve(4000);\r
+        strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";\r
 \r
-    int64 nTime = wtx.GetTxTime();\r
-    int64 nCredit = wtx.GetCredit();\r
-    int64 nDebit = wtx.GetDebit();\r
-    int64 nNet = nCredit - nDebit;\r
+        int64 nTime = wtx.GetTxTime();\r
+        int64 nCredit = wtx.GetCredit();\r
+        int64 nDebit = wtx.GetDebit();\r
+        int64 nNet = nCredit - nDebit;\r
 \r
 \r
 \r
-    strHTML += "<b>Status:</b> " + FormatTxStatus(wtx);\r
-    int nRequests = wtx.GetRequestCount();\r
-    if (nRequests != -1)\r
-    {\r
-        if (nRequests == 0)\r
-            strHTML += ", has not been successfully broadcast yet";\r
-        else if (nRequests == 1)\r
-            strHTML += strprintf(", broadcast through %d node", nRequests);\r
-        else\r
-            strHTML += strprintf(", broadcast through %d nodes", nRequests);\r
-    }\r
-    strHTML += "<br>";\r
+        strHTML += "<b>Status:</b> " + FormatTxStatus(wtx);\r
+        int nRequests = wtx.GetRequestCount();\r
+        if (nRequests != -1)\r
+        {\r
+            if (nRequests == 0)\r
+                strHTML += ", has not been successfully broadcast yet";\r
+            else if (nRequests == 1)\r
+                strHTML += strprintf(", broadcast through %d node", nRequests);\r
+            else\r
+                strHTML += strprintf(", broadcast through %d nodes", nRequests);\r
+        }\r
+        strHTML += "<br>";\r
 \r
-    strHTML += "<b>Date:</b> " + (nTime ? DateTimeStr(nTime) : "") + "<br>";\r
+        strHTML += "<b>Date:</b> " + (nTime ? DateTimeStr(nTime) : "") + "<br>";\r
 \r
 \r
-    //\r
-    // From\r
-    //\r
-    if (wtx.IsCoinBase())\r
-    {\r
-        strHTML += "<b>Source:</b> Generated<br>";\r
-    }\r
-    else if (!wtx.mapValue["from"].empty())\r
-    {\r
-        // Online transaction\r
-        if (!wtx.mapValue["from"].empty())\r
-            strHTML += "<b>From:</b> " + HtmlEscape(wtx.mapValue["from"]) + "<br>";\r
-    }\r
-    else\r
-    {\r
-        // Offline transaction\r
-        if (nNet > 0)\r
+        //\r
+        // From\r
+        //\r
+        if (wtx.IsCoinBase())\r
         {\r
-            // Credit\r
-            foreach(const CTxOut& txout, wtx.vout)\r
+            strHTML += "<b>Source:</b> Generated<br>";\r
+        }\r
+        else if (!wtx.mapValue["from"].empty())\r
+        {\r
+            // Online transaction\r
+            if (!wtx.mapValue["from"].empty())\r
+                strHTML += "<b>From:</b> " + HtmlEscape(wtx.mapValue["from"]) + "<br>";\r
+        }\r
+        else\r
+        {\r
+            // Offline transaction\r
+            if (nNet > 0)\r
             {\r
-                if (txout.IsMine())\r
+                // Credit\r
+                foreach(const CTxOut& txout, wtx.vout)\r
                 {\r
-                    vector<unsigned char> vchPubKey;\r
-                    if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))\r
+                    if (txout.IsMine())\r
                     {\r
-                        string strAddress = PubKeyToAddress(vchPubKey);\r
-                        if (mapAddressBook.count(strAddress))\r
+                        vector<unsigned char> vchPubKey;\r
+                        if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))\r
                         {\r
-                            strHTML += "<b>From:</b> unknown<br>";\r
-                            strHTML += "<b>To:</b> ";\r
-                            strHTML += HtmlEscape(strAddress);\r
-                            if (!mapAddressBook[strAddress].empty())\r
-                                strHTML += " (yours, label: " + mapAddressBook[strAddress] + ")";\r
-                            else\r
-                                strHTML += " (yours)";\r
-                            strHTML += "<br>";\r
+                            string strAddress = PubKeyToAddress(vchPubKey);\r
+                            if (mapAddressBook.count(strAddress))\r
+                            {\r
+                                strHTML += "<b>From:</b> unknown<br>";\r
+                                strHTML += "<b>To:</b> ";\r
+                                strHTML += HtmlEscape(strAddress);\r
+                                if (!mapAddressBook[strAddress].empty())\r
+                                    strHTML += " (yours, label: " + mapAddressBook[strAddress] + ")";\r
+                                else\r
+                                    strHTML += " (yours)";\r
+                                strHTML += "<br>";\r
+                            }\r
                         }\r
+                        break;\r
                     }\r
-                    break;\r
                 }\r
             }\r
         }\r
-    }\r
 \r
 \r
-    //\r
-    // To\r
-    //\r
-    string strAddress;\r
-    if (!wtx.mapValue["to"].empty())\r
-    {\r
-        // Online transaction\r
-        strAddress = wtx.mapValue["to"];\r
-        strHTML += "<b>To:</b> ";\r
-        if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())\r
-            strHTML += mapAddressBook[strAddress] + " ";\r
-        strHTML += HtmlEscape(strAddress) + "<br>";\r
-    }\r
-\r
-\r
-    //\r
-    // Amount\r
-    //\r
-    if (wtx.IsCoinBase() && nCredit == 0)\r
-    {\r
-        //\r
-        // Coinbase\r
-        //\r
-        int64 nUnmatured = 0;\r
-        foreach(const CTxOut& txout, wtx.vout)\r
-            nUnmatured += txout.GetCredit();\r
-        if (wtx.IsInMainChain())\r
-            strHTML += strprintf("<b>Credit:</b> (%s matures in %d more blocks)<br>", FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());\r
-        else\r
-            strHTML += "<b>Credit:</b> (not accepted)<br>";\r
-    }\r
-    else if (nNet > 0)\r
-    {\r
         //\r
-        // Credit\r
+        // To\r
         //\r
-        strHTML += "<b>Credit:</b> " + FormatMoney(nNet) + "<br>";\r
-    }\r
-    else\r
-    {\r
-        bool fAllFromMe = true;\r
-        foreach(const CTxIn& txin, wtx.vin)\r
-            fAllFromMe = fAllFromMe && txin.IsMine();\r
+        string strAddress;\r
+        if (!wtx.mapValue["to"].empty())\r
+        {\r
+            // Online transaction\r
+            strAddress = wtx.mapValue["to"];\r
+            strHTML += "<b>To:</b> ";\r
+            if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())\r
+                strHTML += mapAddressBook[strAddress] + " ";\r
+            strHTML += HtmlEscape(strAddress) + "<br>";\r
+        }\r
 \r
-        bool fAllToMe = true;\r
-        foreach(const CTxOut& txout, wtx.vout)\r
-            fAllToMe = fAllToMe && txout.IsMine();\r
 \r
-        if (fAllFromMe)\r
+        //\r
+        // Amount\r
+        //\r
+        if (wtx.IsCoinBase() && nCredit == 0)\r
         {\r
             //\r
-            // Debit\r
+            // Coinbase\r
             //\r
+            int64 nUnmatured = 0;\r
             foreach(const CTxOut& txout, wtx.vout)\r
-            {\r
-                if (txout.IsMine())\r
-                    continue;\r
+                nUnmatured += txout.GetCredit();\r
+            if (wtx.IsInMainChain())\r
+                strHTML += strprintf("<b>Credit:</b> (%s matures in %d more blocks)<br>", FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());\r
+            else\r
+                strHTML += "<b>Credit:</b> (not accepted)<br>";\r
+        }\r
+        else if (nNet > 0)\r
+        {\r
+            //\r
+            // Credit\r
+            //\r
+            strHTML += "<b>Credit:</b> " + FormatMoney(nNet) + "<br>";\r
+        }\r
+        else\r
+        {\r
+            bool fAllFromMe = true;\r
+            foreach(const CTxIn& txin, wtx.vin)\r
+                fAllFromMe = fAllFromMe && txin.IsMine();\r
+\r
+            bool fAllToMe = true;\r
+            foreach(const CTxOut& txout, wtx.vout)\r
+                fAllToMe = fAllToMe && txout.IsMine();\r
 \r
-                if (wtx.mapValue["to"].empty())\r
+            if (fAllFromMe)\r
+            {\r
+                //\r
+                // Debit\r
+                //\r
+                foreach(const CTxOut& txout, wtx.vout)\r
                 {\r
-                    // Offline transaction\r
-                    uint160 hash160;\r
-                    if (ExtractHash160(txout.scriptPubKey, hash160))\r
+                    if (txout.IsMine())\r
+                        continue;\r
+\r
+                    if (wtx.mapValue["to"].empty())\r
                     {\r
-                        string strAddress = Hash160ToAddress(hash160);\r
-                        strHTML += "<b>To:</b> ";\r
-                        if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())\r
-                            strHTML += mapAddressBook[strAddress] + " ";\r
-                        strHTML += strAddress;\r
-                        strHTML += "<br>";\r
+                        // Offline transaction\r
+                        uint160 hash160;\r
+                        if (ExtractHash160(txout.scriptPubKey, hash160))\r
+                        {\r
+                            string strAddress = Hash160ToAddress(hash160);\r
+                            strHTML += "<b>To:</b> ";\r
+                            if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())\r
+                                strHTML += mapAddressBook[strAddress] + " ";\r
+                            strHTML += strAddress;\r
+                            strHTML += "<br>";\r
+                        }\r
                     }\r
+\r
+                    strHTML += "<b>Debit:</b> " + FormatMoney(-txout.nValue) + "<br>";\r
                 }\r
 \r
-                strHTML += "<b>Debit:</b> " + FormatMoney(-txout.nValue) + "<br>";\r
-            }\r
+                if (fAllToMe)\r
+                {\r
+                    // Payment to self\r
+                    /// issue: can't tell which is the payment and which is the change anymore\r
+                    //int64 nValue = wtx.vout[0].nValue;\r
+                    //strHTML += "<b>Debit:</b> " + FormatMoney(-nValue) + "<br>";\r
+                    //strHTML += "<b>Credit:</b> " + FormatMoney(nValue) + "<br>";\r
+                }\r
 \r
-            if (fAllToMe)\r
+                int64 nTxFee = nDebit - wtx.GetValueOut();\r
+                if (nTxFee > 0)\r
+                    strHTML += "<b>Transaction fee:</b> " + FormatMoney(-nTxFee) + "<br>";\r
+            }\r
+            else\r
             {\r
-                // Payment to self\r
-                /// issue: can't tell which is the payment and which is the change anymore\r
-                //int64 nValue = wtx.vout[0].nValue;\r
-                //strHTML += "<b>Debit:</b> " + FormatMoney(-nValue) + "<br>";\r
-                //strHTML += "<b>Credit:</b> " + FormatMoney(nValue) + "<br>";\r
+                //\r
+                // Mixed debit transaction\r
+                //\r
+                foreach(const CTxIn& txin, wtx.vin)\r
+                    if (txin.IsMine())\r
+                        strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>";\r
+                foreach(const CTxOut& txout, wtx.vout)\r
+                    if (txout.IsMine())\r
+                        strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";\r
             }\r
-\r
-            int64 nTxFee = nDebit - wtx.GetValueOut();\r
-            if (nTxFee > 0)\r
-                strHTML += "<b>Transaction fee:</b> " + FormatMoney(-nTxFee) + "<br>";\r
         }\r
-        else\r
-        {\r
-            //\r
-            // Mixed debit transaction\r
-            //\r
-            foreach(const CTxIn& txin, wtx.vin)\r
-                if (txin.IsMine())\r
-                    strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>";\r
-            foreach(const CTxOut& txout, wtx.vout)\r
-                if (txout.IsMine())\r
-                    strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";\r
-        }\r
-    }\r
 \r
-    strHTML += "<b>Net amount:</b> " + FormatMoney(nNet, true) + "<br>";\r
+        strHTML += "<b>Net amount:</b> " + FormatMoney(nNet, true) + "<br>";\r
 \r
 \r
-    //\r
-    // Message\r
-    //\r
-    if (!wtx.mapValue["message"].empty())\r
-        strHTML += "<br><b>Message:</b><br>" + HtmlEscape(wtx.mapValue["message"], true) + "<br>";\r
-\r
-    if (wtx.IsCoinBase())\r
-        strHTML += "<br>Generated coins must wait 120 blocks before they can be spent.  When you generated this block, it was broadcast to the network to be added to the block chain.  If it fails to get into the chain, it will change to \"not accepted\" and not be spendable.  This may occasionally happen if another node generates a block within a few seconds of yours.<br>";\r
+        //\r
+        // Message\r
+        //\r
+        if (!wtx.mapValue["message"].empty())\r
+            strHTML += "<br><b>Message:</b><br>" + HtmlEscape(wtx.mapValue["message"], true) + "<br>";\r
 \r
+        if (wtx.IsCoinBase())\r
+            strHTML += "<br>Generated coins must wait 120 blocks before they can be spent.  When you generated this block, it was broadcast to the network to be added to the block chain.  If it fails to get into the chain, it will change to \"not accepted\" and not be spendable.  This may occasionally happen if another node generates a block within a few seconds of yours.<br>";\r
 \r
-    //\r
-    // Debug view\r
-    //\r
-    if (fDebug)\r
-    {\r
-        strHTML += "<hr><br>debug print<br><br>";\r
-        foreach(const CTxIn& txin, wtx.vin)\r
-            if (txin.IsMine())\r
-                strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>";\r
-        foreach(const CTxOut& txout, wtx.vout)\r
-            if (txout.IsMine())\r
-                strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";\r
 \r
-        strHTML += "<b>Inputs:</b><br>";\r
-        CRITICAL_BLOCK(cs_mapWallet)\r
+        //\r
+        // Debug view\r
+        //\r
+        if (fDebug)\r
         {\r
+            strHTML += "<hr><br>debug print<br><br>";\r
             foreach(const CTxIn& txin, wtx.vin)\r
+                if (txin.IsMine())\r
+                    strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>";\r
+            foreach(const CTxOut& txout, wtx.vout)\r
+                if (txout.IsMine())\r
+                    strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";\r
+\r
+            strHTML += "<b>Inputs:</b><br>";\r
+            CRITICAL_BLOCK(cs_mapWallet)\r
             {\r
-                COutPoint prevout = txin.prevout;\r
-                map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);\r
-                if (mi != mapWallet.end())\r
+                foreach(const CTxIn& txin, wtx.vin)\r
                 {\r
-                    const CWalletTx& prev = (*mi).second;\r
-                    if (prevout.n < prev.vout.size())\r
+                    COutPoint prevout = txin.prevout;\r
+                    map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);\r
+                    if (mi != mapWallet.end())\r
                     {\r
-                        strHTML += HtmlEscape(prev.ToString(), true);\r
-                        strHTML += " &nbsp;&nbsp; " + FormatTxStatus(prev) + ", ";\r
-                        strHTML = strHTML + "IsMine=" + (prev.vout[prevout.n].IsMine() ? "true" : "false") + "<br>";\r
+                        const CWalletTx& prev = (*mi).second;\r
+                        if (prevout.n < prev.vout.size())\r
+                        {\r
+                            strHTML += HtmlEscape(prev.ToString(), true);\r
+                            strHTML += " &nbsp;&nbsp; " + FormatTxStatus(prev) + ", ";\r
+                            strHTML = strHTML + "IsMine=" + (prev.vout[prevout.n].IsMine() ? "true" : "false") + "<br>";\r
+                        }\r
                     }\r
                 }\r
             }\r
-        }\r
 \r
-        strHTML += "<br><hr><br><b>Transaction:</b><br>";\r
-        strHTML += HtmlEscape(wtx.ToString(), true);\r
-    }\r
+            strHTML += "<br><hr><br><b>Transaction:</b><br>";\r
+            strHTML += HtmlEscape(wtx.ToString(), true);\r
+        }\r
 \r
 \r
 \r
-    strHTML += "</font></html>";\r
-    string(strHTML.begin(), strHTML.end()).swap(strHTML);\r
-    m_htmlWin->SetPage(strHTML);\r
-    m_buttonOK->SetFocus();\r
+        strHTML += "</font></html>";\r
+        string(strHTML.begin(), strHTML.end()).swap(strHTML);\r
+        m_htmlWin->SetPage(strHTML);\r
+        m_buttonOK->SetFocus();\r
+    }\r
 }\r
 \r
 void CTxDetailsDialog::OnButtonOK(wxCommandEvent& event)\r
@@ -1686,9 +1695,10 @@ CAboutDialog::CAboutDialog(wxWindow* parent) : CAboutDialogBase(parent)
 \r
 #if !wxUSE_UNICODE\r
     // Workaround until upgrade to wxWidgets supporting UTF-8\r
+    // Hack to change the (c) character from UTF-8 back to ANSI\r
     wxString str = m_staticTextMain->GetLabel();\r
-    if (str.Find('Â') != wxNOT_FOUND)\r
-        str.Remove(str.Find('Â'), 1);\r
+    if (str.Find('\xC2') != wxNOT_FOUND)\r
+        str.Remove(str.Find('\xC2'), 1);\r
     m_staticTextMain->SetLabel(str);\r
 #endif\r
 #ifndef __WXMSW__\r
@@ -1843,10 +1853,11 @@ void CSendDialog::OnButtonSend(wxCommandEvent& event)
         CScript scriptPubKey;\r
         scriptPubKey << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;\r
 \r
-        if (!SendMoney(scriptPubKey, nValue, wtx))\r
-            return;\r
-\r
-        wxMessageBox("Payment sent  ", "Sending...");\r
+        string strError = SendMoney(scriptPubKey, nValue, wtx);\r
+        if (strError != "")\r
+            wxMessageBox(strError + "  ", "Sending...");\r
+        else\r
+            wxMessageBox("Payment sent  ", "Sending...");\r
     }\r
     else\r
     {\r
@@ -1869,8 +1880,9 @@ void CSendDialog::OnButtonSend(wxCommandEvent& event)
             return;\r
     }\r
 \r
-    if (!mapAddressBook.count(strAddress))\r
-        SetAddressBookName(strAddress, "");\r
+    CRITICAL_BLOCK(cs_mapAddressBook)\r
+        if (!mapAddressBook.count(strAddress))\r
+            SetAddressBookName(strAddress, "");\r
 \r
     EndModal(true);\r
 }\r
@@ -2227,6 +2239,7 @@ CYourAddressDialog::CYourAddressDialog(wxWindow* parent, const string& strInitSe
 \r
     // Fill listctrl with address book data\r
     CRITICAL_BLOCK(cs_mapKeys)\r
+    CRITICAL_BLOCK(cs_mapAddressBook)\r
     {\r
         foreach(const PAIRTYPE(string, string)& item, mapAddressBook)\r
         {\r
@@ -2366,6 +2379,7 @@ CAddressBookDialog::CAddressBookDialog(wxWindow* parent, const wxString& strInit
 \r
     // Fill listctrl with address book data\r
     CRITICAL_BLOCK(cs_mapKeys)\r
+    CRITICAL_BLOCK(cs_mapAddressBook)\r
     {\r
         foreach(const PAIRTYPE(string, string)& item, mapAddressBook)\r
         {\r
@@ -3515,6 +3529,12 @@ bool CMyApp::OnInit2()
     //\r
     // Parameters\r
     //\r
+    if (argc > 1 && argv[1][0] != '-' && argv[1][0] != '/')\r
+    {\r
+        int ret = CommandLineRPC(argc, argv);\r
+        exit(ret);\r
+    }\r
+\r
     ParseParameters(argc, argv);\r
     if (mapArgs.count("-?") || mapArgs.count("--help"))\r
     {\r
@@ -3557,6 +3577,13 @@ bool CMyApp::OnInit2()
     if (mapArgs.count("-printtodebugger"))\r
         fPrintToDebugger = true;\r
 \r
+    if (mapArgs.count("-daemon") || mapArgs.count("-d"))\r
+    {\r
+        fDaemon = true;\r
+        /// todo: need to fork\r
+        ///  should it fork after the bind/single instance stuff?\r
+    }\r
+\r
     if (!fDebug && !pszSetDataDir[0])\r
         ShrinkDebugFile();\r
     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");\r
@@ -3730,7 +3757,7 @@ bool CMyApp::OnInit2()
     //\r
     // Create the main frame window\r
     //\r
-    if (!mapArgs.count("-noui"))\r
+    if (!fDaemon)\r
     {\r
         pframeMain = new CMainFrame(NULL);\r
         if (mapArgs.count("-min"))\r
@@ -3752,6 +3779,9 @@ bool CMyApp::OnInit2()
     if (!CreateThread(StartNode, NULL))\r
         wxMessageBox("Error: CreateThread(StartNode) failed", "Bitcoin");\r
 \r
+    if (mapArgs.count("-server") || fDaemon)\r
+        CreateThread(ThreadRPCServer, NULL);\r
+\r
     if (fFirstRun)\r
         SetStartOnSystemStartup(true);\r
 \r
index 4292246..2f5be22 100644 (file)
--- a/util.cpp
+++ b/util.cpp
@@ -1,4 +1,4 @@
-// Copyright (c) 2009 Satoshi Nakamoto\r
+// Copyright (c) 2009-2010 Satoshi Nakamoto\r
 // Distributed under the MIT/X11 software license, see the accompanying\r
 // file license.txt or http://www.opensource.org/licenses/mit-license.php.\r
 \r
@@ -12,6 +12,7 @@ bool fPrintToConsole = false;
 bool fPrintToDebugger = false;\r
 char pszSetDataDir[MAX_PATH] = "";\r
 bool fShutdown = false;\r
+bool fDaemon = false;\r
 \r
 \r
 \r
diff --git a/util.h b/util.h
index d20648b..6a7fabc 100644 (file)
--- a/util.h
+++ b/util.h
@@ -1,4 +1,4 @@
-// Copyright (c) 2009 Satoshi Nakamoto\r
+// Copyright (c) 2009-2010 Satoshi Nakamoto\r
 // Distributed under the MIT/X11 software license, see the accompanying\r
 // file license.txt or http://www.opensource.org/licenses/mit-license.php.\r
 \r
@@ -55,6 +55,7 @@ inline T& REF(const T& val)
 }\r
 \r
 #ifdef __WXMSW__\r
+static const bool fWindows = true;\r
 #define MSG_NOSIGNAL        0\r
 #define MSG_DONTWAIT        0\r
 #ifndef UINT64_MAX\r
@@ -66,7 +67,9 @@ inline T& REF(const T& val)
 #define S_IRUSR             0400\r
 #define S_IWUSR             0200\r
 #endif\r
+#define unlink              _unlink\r
 #else\r
+static const bool fWindows = false;\r
 #define WSAGetLastError()   errno\r
 #define WSAEWOULDBLOCK      EWOULDBLOCK\r
 #define WSAEMSGSIZE         EMSGSIZE\r
@@ -116,6 +119,7 @@ extern bool fPrintToConsole;
 extern bool fPrintToDebugger;\r
 extern char pszSetDataDir[MAX_PATH];\r
 extern bool fShutdown;\r
+extern bool fDaemon;\r
 \r
 void RandAddSeed();\r
 void RandAddSeedPerfmon();\r
@@ -258,6 +262,11 @@ inline int roundint(double d)
     return (int)(d > 0 ? d + 0.5 : d - 0.5);\r
 }\r
 \r
+inline int64 roundint64(double d)\r
+{\r
+    return (int64)(d > 0 ? d + 0.5 : d - 0.5);\r
+}\r
+\r
 template<typename T>\r
 string HexStr(const T itbegin, const T itend, bool fSpaces=true)\r
 {\r
@@ -323,7 +332,12 @@ inline string DateTimeStrFormat(const char* pszFormat, int64 nTime)
     return pszTime;\r
 }\r
 \r
-\r
+template<typename T>\r
+void skipspaces(T& it)\r
+{\r
+    while (isspace(*it))\r
+        ++it;\r
+}\r
 \r
 \r
 \r