What changed
Bitcoin v0.3.23 → v0.3.24
Release commit message: Compile 'sv' translation
Previous diff: v0.3.22 → v0.3.23.
- db.cpp modified · +46 −132
- db.h modified · +25 −95
- headers.h modified · +1 −31
- init.cpp modified · +38 −11
- init.h modified · +2 −0
- irc.cpp modified · +3 −0
- keystore.cpp added · +33 −0
- keystore.h added · +30 −0
- main.cpp modified · +326 −1240
- main.h modified · +44 −536
- makefile.linux-mingw added · +111 −0
- makefile.mingw modified · +11 −1
- makefile.osx modified · +10 −2
- makefile.unix modified · +10 −3
- makefile.vc modified · +35 −9
- net.cpp modified · +36 −18
- net.h modified · +2 −0
- noui.h modified · +2 −0
- rpc.cpp modified · +110 −93
- script.cpp modified · +18 −21
- script.h modified · +4 −4
- serialize.h modified · +1 −1
- ui.cpp modified · +109 −97
- ui.h modified · +3 −0
- util.cpp modified · +12 −9
- util.h modified · +0 −1
- wallet.cpp added · +1140 −1
- wallet.h added · +615 −1
db.cpp (modified)
1--- v0.3.23/db.cpp2+++ v0.3.24/db.cpp3@@ -3,11 +3,13 @@4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.5 6 #include "headers.h"7+#include "db.h"8+#include "net.h"9+#include <boost/filesystem.hpp>10+#include <boost/filesystem/fstream.hpp>11 12 using namespace std;13 using namespace boost;14-15-void ThreadFlushWalletDB(void* parg);16 17 18 unsigned int nWalletDBUpdated;19@@ -147,7 +149,7 @@20 --mapFileUseCount[strFile];21 }22 23-void CloseDb(const string& strFile)24+void static CloseDb(const string& strFile)25 {26 CRITICAL_BLOCK(cs_db)27 {28@@ -356,7 +358,7 @@29 return Write(string("bnBestInvalidWork"), bnBestInvalidWork);30 }31 32-CBlockIndex* InsertBlockIndex(uint256 hash)33+CBlockIndex static * InsertBlockIndex(uint256 hash)34 {35 if (hash == 0)36 return NULL;37@@ -581,8 +583,19 @@38 // CWalletDB39 //40 41-static set<int64> setKeyPool;42-static CCriticalSection cs_setKeyPool;43+bool CWalletDB::WriteName(const string& strAddress, const string& strName)44+{45+ nWalletDBUpdated++;46+ return Write(make_pair(string("name"), strAddress), strName);47+}48+49+bool CWalletDB::EraseName(const string& strAddress)50+{51+ // This should only be used for sending addresses, never for receiving addresses,52+ // receiving addresses must always have an address book entry if they're not change return.53+ nWalletDBUpdated++;54+ return Erase(make_pair(string("name"), strAddress));55+}56 57 bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)58 {59@@ -657,9 +670,9 @@60 }61 62 63-bool CWalletDB::LoadWallet()64-{65- vchDefaultKey.clear();66+bool CWalletDB::LoadWallet(CWallet* pwallet)67+{68+ pwallet->vchDefaultKey.clear();69 int nFileVersion = 0;70 vector<uint256> vWalletUpgrade;71 72@@ -671,8 +684,8 @@73 #endif74 75 //// todo: shouldn't we catch exceptions and try to recover and continue?76- CRITICAL_BLOCK(cs_mapWallet)77- CRITICAL_BLOCK(cs_mapKeys)78+ CRITICAL_BLOCK(pwallet->cs_mapWallet)79+ CRITICAL_BLOCK(pwallet->cs_mapKeys)80 {81 // Get cursor82 Dbc* pcursor = GetCursor();83@@ -699,14 +712,15 @@84 {85 string strAddress;86 ssKey >> strAddress;87- ssValue >> mapAddressBook[strAddress];88+ ssValue >> pwallet->mapAddressBook[strAddress];89 }90 else if (strType == "tx")91 {92 uint256 hash;93 ssKey >> hash;94- CWalletTx& wtx = mapWallet[hash];95+ CWalletTx& wtx = pwallet->mapWallet[hash];96 ssValue >> wtx;97+ wtx.pwallet = pwallet;98 99 if (wtx.GetHash() != hash)100 printf("Error in wallet.dat, hash mismatch\n");101@@ -757,18 +771,18 @@102 else103 ssValue >> wkey;104 105- mapKeys[vchPubKey] = wkey.vchPrivKey;106+ pwallet->mapKeys[vchPubKey] = wkey.vchPrivKey;107 mapPubKeys[Hash160(vchPubKey)] = vchPubKey;108 }109 else if (strType == "defaultkey")110 {111- ssValue >> vchDefaultKey;112+ ssValue >> pwallet->vchDefaultKey;113 }114 else if (strType == "pool")115 {116 int64 nIndex;117 ssKey >> nIndex;118- setKeyPool.insert(nIndex);119+ pwallet->setKeyPool.insert(nIndex);120 }121 else if (strType == "version")122 {123@@ -800,7 +814,7 @@124 }125 126 BOOST_FOREACH(uint256 hash, vWalletUpgrade)127- WriteTx(hash, mapWallet[hash]);128+ WriteTx(hash, pwallet->mapWallet[hash]);129 130 printf("nFileVersion = %d\n", nFileVersion);131 printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);132@@ -828,36 +842,9 @@133 return true;134 }135 136-bool LoadWallet(bool& fFirstRunRet)137-{138- fFirstRunRet = false;139- if (!CWalletDB("cr+").LoadWallet())140- return false;141- fFirstRunRet = vchDefaultKey.empty();142-143- if (mapKeys.count(vchDefaultKey))144- {145- // Set keyUser146- keyUser.SetPubKey(vchDefaultKey);147- keyUser.SetPrivKey(mapKeys[vchDefaultKey]);148- }149- else150- {151- // Create new keyUser and set as default key152- RandAddSeedPerfmon();153-154- CWalletDB walletdb;155- vchDefaultKey = GetKeyFromKeyPool();156- walletdb.WriteDefaultKey(vchDefaultKey);157- walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");158- }159-160- CreateThread(ThreadFlushWalletDB, NULL);161- return true;162-}163-164 void ThreadFlushWalletDB(void* parg)165 {166+ const string& strFile = ((const string*)parg)[0];167 static bool fOneThread;168 if (fOneThread)169 return;170@@ -893,7 +880,6 @@171 172 if (nRefCount == 0 && !fShutdown)173 {174- string strFile = "wallet.dat";175 map<string, int>::iterator mi = mapFileUseCount.find(strFile);176 if (mi != mapFileUseCount.end())177 {178@@ -916,26 +902,27 @@179 }180 }181 182-void BackupWallet(const string& strDest)183-{184+bool BackupWallet(const CWallet& wallet, const string& strDest)185+{186+ if (!wallet.fFileBacked)187+ return false;188 while (!fShutdown)189 {190 CRITICAL_BLOCK(cs_db)191 {192- const string strFile = "wallet.dat";193- if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)194+ if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)195 {196 // Flush log data to the dat file197- CloseDb(strFile);198+ CloseDb(wallet.strWalletFile);199 dbenv.txn_checkpoint(0, 0, 0);200- dbenv.lsn_reset(strFile.c_str(), 0);201- mapFileUseCount.erase(strFile);202+ dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);203+ mapFileUseCount.erase(wallet.strWalletFile);204 205 // Copy wallet.dat206- filesystem::path pathSrc(GetDataDir() + "/" + strFile);207+ filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);208 filesystem::path pathDest(strDest);209 if (filesystem::is_directory(pathDest))210- pathDest = pathDest / strFile;211+ pathDest = pathDest / wallet.strWalletFile;212 #if BOOST_VERSION >= 104000213 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);214 #else215@@ -943,84 +930,11 @@216 #endif217 printf("copied wallet.dat to %s\n", pathDest.string().c_str());218 219- return;220+ return true;221 }222 }223 Sleep(100);224 }225-}226-227-228-void CWalletDB::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)229-{230- nIndex = -1;231- keypool.vchPubKey.clear();232- CRITICAL_BLOCK(cs_main)233- CRITICAL_BLOCK(cs_mapWallet)234- CRITICAL_BLOCK(cs_setKeyPool)235- {236- // Top up key pool237- int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);238- while (setKeyPool.size() < nTargetSize+1)239- {240- int64 nEnd = 1;241- if (!setKeyPool.empty())242- nEnd = *(--setKeyPool.end()) + 1;243- if (!Write(make_pair(string("pool"), nEnd), CKeyPool(GenerateNewKey())))244- throw runtime_error("ReserveKeyFromKeyPool() : writing generated key failed");245- setKeyPool.insert(nEnd);246- printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());247- }248-249- // Get the oldest key250- assert(!setKeyPool.empty());251- nIndex = *(setKeyPool.begin());252- setKeyPool.erase(setKeyPool.begin());253- if (!Read(make_pair(string("pool"), nIndex), keypool))254- throw runtime_error("ReserveKeyFromKeyPool() : read failed");255- if (!mapKeys.count(keypool.vchPubKey))256- throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");257- assert(!keypool.vchPubKey.empty());258- printf("keypool reserve %"PRI64d"\n", nIndex);259- }260-}261-262-void CWalletDB::KeepKey(int64 nIndex)263-{264- // Remove from key pool265- CRITICAL_BLOCK(cs_main)266- CRITICAL_BLOCK(cs_mapWallet)267- {268- Erase(make_pair(string("pool"), nIndex));269- }270- printf("keypool keep %"PRI64d"\n", nIndex);271-}272-273-void CWalletDB::ReturnKey(int64 nIndex)274-{275- // Return to key pool276- CRITICAL_BLOCK(cs_setKeyPool)277- setKeyPool.insert(nIndex);278- printf("keypool return %"PRI64d"\n", nIndex);279-}280-281-vector<unsigned char> GetKeyFromKeyPool()282-{283- CWalletDB walletdb;284- int64 nIndex = 0;285- CKeyPool keypool;286- walletdb.ReserveKeyFromKeyPool(nIndex, keypool);287- walletdb.KeepKey(nIndex);288- return keypool.vchPubKey;289-}290-291-int64 GetOldestKeyPoolTime()292-{293- CWalletDB walletdb;294- int64 nIndex = 0;295- CKeyPool keypool;296- walletdb.ReserveKeyFromKeyPool(nIndex, keypool);297- walletdb.ReturnKey(nIndex);298- return keypool.nTime;299-}300-301+ return false;302+}303+
db.h (modified)
1--- v0.3.23/db.h2+++ v0.3.24/db.h3@@ -12,33 +12,25 @@4 5 #include <db_cxx.h>6 7-class CTransaction;8 class CTxIndex;9 class CDiskBlockIndex;10 class CDiskTxPos;11 class COutPoint;12-class CUser;13-class CReview;14 class CAddress;15 class CWalletTx;16+class CWallet;17 class CAccount;18 class CAccountingEntry;19 class CBlockLocator;20 21-extern std::map<std::string, std::string> mapAddressBook;22-extern CCriticalSection cs_mapAddressBook;23-extern std::vector<unsigned char> vchDefaultKey;24-extern bool fClient;25-extern int nBestHeight;26-27 28 extern unsigned int nWalletDBUpdated;29 extern DbEnv dbenv;30 31 32 extern void DBFlush(bool fShutdown);33-extern std::vector<unsigned char> GetKeyFromKeyPool();34-extern int64 GetOldestKeyPoolTime();35+void ThreadFlushWalletDB(void* parg);36+bool BackupWallet(const CWallet& wallet, const std::string& strDest);37 38 39 40@@ -321,9 +313,6 @@41 42 43 44-45-46-47 class CKeyPool48 {49 public:50@@ -356,7 +345,7 @@51 class CWalletDB : public CDB52 {53 public:54- CWalletDB(const char* pszMode="r+") : CDB("wallet.dat", pszMode)55+ CWalletDB(std::string strFilename, const char* pszMode="r+") : CDB(strFilename.c_str(), pszMode)56 {57 }58 private:59@@ -369,23 +358,9 @@60 return Read(std::make_pair(std::string("name"), strAddress), strName);61 }62 63- bool WriteName(const std::string& strAddress, const std::string& strName)64- {65- CRITICAL_BLOCK(cs_mapAddressBook)66- mapAddressBook[strAddress] = strName;67- nWalletDBUpdated++;68- return Write(std::make_pair(std::string("name"), strAddress), strName);69- }70-71- bool EraseName(const std::string& strAddress)72- {73- // This should only be used for sending addresses, never for receiving addresses,74- // receiving addresses must always have an address book entry if they're not change return.75- CRITICAL_BLOCK(cs_mapAddressBook)76- mapAddressBook.erase(strAddress);77- nWalletDBUpdated++;78- return Erase(std::make_pair(std::string("name"), strAddress));79- }80+ bool WriteName(const std::string& strAddress, const std::string& strName);81+82+ bool EraseName(const std::string& strAddress);83 84 bool ReadTx(uint256 hash, CWalletTx& wtx)85 {86@@ -435,9 +410,25 @@87 88 bool WriteDefaultKey(const std::vector<unsigned char>& vchPubKey)89 {90- vchDefaultKey = vchPubKey;91 nWalletDBUpdated++;92 return Write(std::string("defaultkey"), vchPubKey);93+ }94+95+ bool ReadPool(int64 nPool, CKeyPool& keypool)96+ {97+ return Read(std::make_pair(std::string("pool"), nPool), keypool);98+ }99+100+ bool WritePool(int64 nPool, const CKeyPool& keypool)101+ {102+ nWalletDBUpdated++;103+ return Write(std::make_pair(std::string("pool"), nPool), keypool);104+ }105+106+ bool ErasePool(int64 nPool)107+ {108+ nWalletDBUpdated++;109+ return Erase(std::make_pair(std::string("pool"), nPool));110 }111 112 template<typename T>113@@ -459,69 +450,8 @@114 int64 GetAccountCreditDebit(const std::string& strAccount);115 void ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& acentries);116 117- bool LoadWallet();118-protected:119- void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);120- void KeepKey(int64 nIndex);121- static void ReturnKey(int64 nIndex);122- friend class CReserveKey;123- friend std::vector<unsigned char> GetKeyFromKeyPool();124- friend int64 GetOldestKeyPoolTime();125+ bool LoadWallet(CWallet* pwallet);126 };127 128-bool LoadWallet(bool& fFirstRunRet);129-void BackupWallet(const std::string& strDest);130-131-inline bool SetAddressBookName(const std::string& strAddress, const std::string& strName)132-{133- return CWalletDB().WriteName(strAddress, strName);134-}135-136-class CReserveKey137-{138-protected:139- int64 nIndex;140- std::vector<unsigned char> vchPubKey;141-public:142- CReserveKey()143- {144- nIndex = -1;145- }146-147- ~CReserveKey()148- {149- if (!fShutdown)150- ReturnKey();151- }152-153- std::vector<unsigned char> GetReservedKey()154- {155- if (nIndex == -1)156- {157- CKeyPool keypool;158- CWalletDB().ReserveKeyFromKeyPool(nIndex, keypool);159- vchPubKey = keypool.vchPubKey;160- }161- assert(!vchPubKey.empty());162- return vchPubKey;163- }164-165- void KeepKey()166- {167- if (nIndex != -1)168- CWalletDB().KeepKey(nIndex);169- nIndex = -1;170- vchPubKey.clear();171- }172-173- void ReturnKey()174- {175- if (nIndex != -1)176- CWalletDB::ReturnKey(nIndex);177- nIndex = -1;178- vchPubKey.clear();179- }180-};181-182 #endif183
headers.h (modified)
1--- v0.3.23/headers.h2+++ v0.3.24/headers.h3@@ -48,7 +48,6 @@4 #include <limits.h>5 #include <float.h>6 #include <assert.h>7-#include <memory>8 #include <iostream>9 #include <sstream>10 #include <string>11@@ -56,29 +55,8 @@12 #include <list>13 #include <deque>14 #include <map>15-#include <set>16-#include <algorithm>17-#include <numeric>18+19 #include <boost/foreach.hpp>20-#include <boost/lexical_cast.hpp>21-#include <boost/tuple/tuple.hpp>22-#include <boost/tuple/tuple_comparison.hpp>23-#include <boost/tuple/tuple_io.hpp>24-#include <boost/array.hpp>25-#include <boost/bind.hpp>26-#include <boost/function.hpp>27-#include <boost/filesystem.hpp>28-#include <boost/filesystem/fstream.hpp>29-#include <boost/algorithm/string.hpp>30-#include <boost/thread.hpp>31-#include <boost/interprocess/sync/file_lock.hpp>32-#include <boost/interprocess/sync/interprocess_mutex.hpp>33-#include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>34-#include <boost/date_time/gregorian/gregorian_types.hpp>35-#include <boost/date_time/posix_time/posix_time_types.hpp>36-#include <boost/config.hpp>37-#include <boost/program_options/detail/config_file.hpp>38-#include <boost/program_options/parsers.hpp>39 40 #ifdef __WXMSW__41 #include <windows.h>42@@ -110,26 +88,18 @@43 44 #pragma hdrstop45 46-#include "strlcpy.h"47 #include "serialize.h"48 #include "uint256.h"49 #include "util.h"50-#include "key.h"51 #include "bignum.h"52 #include "base58.h"53-#include "script.h"54-#include "db.h"55-#include "net.h"56-#include "irc.h"57 #include "main.h"58-#include "rpc.h"59 #ifdef GUI60 #include "uibase.h"61 #include "ui.h"62 #else63 #include "noui.h"64 #endif65-#include "init.h"66 67 #ifdef GUI68 #include "xpm/addressbook16.xpm"
init.cpp (modified)
1--- v0.3.23/init.cpp2+++ v0.3.24/init.cpp3@@ -2,9 +2,19 @@4 // Distributed under the MIT/X11 software license, see the accompanying5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.6 #include "headers.h"7+#include "db.h"8+#include "rpc.h"9+#include "net.h"10+#include "init.h"11+#include "strlcpy.h"12+#include <boost/filesystem.hpp>13+#include <boost/filesystem/fstream.hpp>14+#include <boost/interprocess/sync/file_lock.hpp>15 16 using namespace std;17 using namespace boost;18+19+CWallet* pwalletMain;20 21 //////////////////////////////////////////////////////////////////////////////22 //23@@ -38,6 +48,8 @@24 StopNode();25 DBFlush(true);26 boost::filesystem::remove(GetPidFile());27+ UnregisterWallet(pwalletMain);28+ delete pwalletMain;29 CreateThread(ExitTimeout, NULL);30 Sleep(50);31 printf("Bitcoin exiting\n\n");32@@ -129,9 +141,18 @@33 34 if (mapArgs.count("-datadir"))35 {36- filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);37- strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));38- }39+ if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))40+ {41+ filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);42+ strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));43+ }44+ else45+ {46+ fprintf(stderr, "Error: Specified directory does not exist\n");47+ Shutdown(NULL);48+ }49+ }50+51 52 ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir53 54@@ -365,16 +386,19 @@55 printf("Loading wallet...\n");56 nStart = GetTimeMillis();57 bool fFirstRun;58- if (!LoadWallet(fFirstRun))59+ pwalletMain = new CWallet("wallet.dat");60+ if (!pwalletMain->LoadWallet(fFirstRun))61 strErrors += _("Error loading wallet.dat \n");62 printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);63+64+ RegisterWallet(pwalletMain);65 66 CBlockIndex *pindexRescan = pindexBest;67 if (GetBoolArg("-rescan"))68 pindexRescan = pindexGenesisBlock;69 else70 {71- CWalletDB walletdb;72+ CWalletDB walletdb("wallet.dat");73 CBlockLocator locator;74 if (walletdb.ReadBestBlock(locator))75 pindexRescan = locator.GetBlockIndex();76@@ -383,7 +407,7 @@77 {78 printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);79 nStart = GetTimeMillis();80- ScanForWalletTransactions(pindexRescan, true);81+ pwalletMain->ScanForWalletTransactions(pindexRescan, true);82 printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);83 }84 85@@ -392,10 +416,11 @@86 //// debug print87 printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());88 printf("nBestHeight = %d\n", nBestHeight);89- printf("mapKeys.size() = %d\n", mapKeys.size());90+ printf("mapKeys.size() = %d\n", pwalletMain->mapKeys.size());91+ printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());92 printf("mapPubKeys.size() = %d\n", mapPubKeys.size());93- printf("mapWallet.size() = %d\n", mapWallet.size());94- printf("mapAddressBook.size() = %d\n", mapAddressBook.size());95+ printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());96+ printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());97 98 if (!strErrors.empty())99 {100@@ -404,7 +429,7 @@101 }102 103 // Add wallet transactions that aren't already in a block to mapTransactions104- ReacceptWalletTransactions();105+ pwalletMain->ReacceptWalletTransactions();106 107 //108 // Parameters109@@ -469,7 +494,9 @@110 }111 }112 113- if (mapArgs.count("-dnsseed"))114+ if (GetBoolArg("-nodnsseed"))115+ printf("DNS seeding disabled\n");116+ else117 DNSAddressSeed();118 119 if (mapArgs.count("-paytxfee"))
init.h (modified)
1--- v0.3.23/init.h2+++ v0.3.24/init.h3@@ -3,6 +3,8 @@4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.5 #ifndef BITCOIN_INIT_H6 #define BITCOIN_INIT_H7+8+extern CWallet* pwalletMain;9 10 void Shutdown(void* parg);11 bool AppInit(int argc, char* argv[]);
irc.cpp (modified)
1--- v0.3.23/irc.cpp2+++ v0.3.24/irc.cpp3@@ -3,6 +3,9 @@4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.5 6 #include "headers.h"7+#include "irc.h"8+#include "net.h"9+#include "strlcpy.h"10 11 using namespace std;12 using namespace boost;
keystore.cpp (added)
1--- /dev/null2+++ v0.3.24/keystore.cpp3@@ -1 +1,34 @@4+// Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers5+// Distributed under the MIT/X11 software license, see the accompanying6+// file license.txt or http://www.opensource.org/licenses/mit-license.php.7 8+#include "headers.h"9+#include "db.h"10+11+12+13+//////////////////////////////////////////////////////////////////////////////14+//15+// mapKeys16+//17+18+std::vector<unsigned char> CKeyStore::GenerateNewKey()19+{20+ RandAddSeedPerfmon();21+ CKey key;22+ key.MakeNewKey();23+ if (!AddKey(key))24+ throw std::runtime_error("GenerateNewKey() : AddKey failed");25+ return key.GetPubKey();26+}27+28+bool CKeyStore::AddKey(const CKey& key)29+{30+ CRITICAL_BLOCK(cs_mapKeys)31+ {32+ mapKeys[key.GetPubKey()] = key.GetPrivKey();33+ mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();34+ }35+}36+37+
keystore.h (added)
1--- /dev/null2+++ v0.3.24/keystore.h3@@ -1 +1,31 @@4+// Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers5+// Distributed under the MIT/X11 software license, see the accompanying6+// file license.txt or http://www.opensource.org/licenses/mit-license.php.7+#ifndef BITCOIN_KEYSTORE_H8+#define BITCOIN_KEYSTORE_H9 10+class CKeyStore11+{12+public:13+ std::map<std::vector<unsigned char>, CPrivKey> mapKeys;14+ mutable CCriticalSection cs_mapKeys;15+ virtual bool AddKey(const CKey& key);16+ bool HaveKey(const std::vector<unsigned char> &vchPubKey) const17+ {18+ return (mapKeys.count(vchPubKey) > 0);19+ }20+ bool GetPrivKey(const std::vector<unsigned char> &vchPubKey, CPrivKey& keyOut) const21+ {22+ std::map<std::vector<unsigned char>, CPrivKey>::const_iterator mi = mapKeys.find(vchPubKey);23+ if (mi != mapKeys.end())24+ {25+ keyOut = (*mi).second;26+ return true;27+ }28+ return false;29+ }30+ std::vector<unsigned char> GenerateNewKey();31+};32+33+#endif34+
main.cpp (modified)
1--- v0.3.23/main.cpp2+++ v0.3.24/main.cpp3@@ -2,7 +2,12 @@4 // Distributed under the MIT/X11 software license, see the accompanying5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.6 #include "headers.h"7+#include "db.h"8+#include "net.h"9+#include "init.h"10 #include "cryptopp/sha.h"11+#include <boost/filesystem.hpp>12+#include <boost/filesystem/fstream.hpp>13 14 using namespace std;15 using namespace boost;16@@ -11,7 +16,13 @@17 // Global state18 //19 20+CCriticalSection cs_setpwalletRegistered;21+set<CWallet*> setpwalletRegistered;22+23 CCriticalSection cs_main;24+25+CCriticalSection cs_mapPubKeys;26+map<uint160, vector<unsigned char> > mapPubKeys;27 28 map<uint256, CTransaction> mapTransactions;29 CCriticalSection cs_mapTransactions;30@@ -21,6 +32,8 @@31 map<uint256, CBlockIndex*> mapBlockIndex;32 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");33 CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);34+const int nTotalBlocksEstimate = 134444; // Conservative estimate of total nr of blocks on main chain35+const int nInitialBlockThreshold = 120; // Regard blocks up until N-threshold as "initial download"36 CBlockIndex* pindexGenesisBlock = NULL;37 int nBestHeight = -1;38 CBigNum bnBestChainWork = 0;39@@ -35,22 +48,6 @@40 map<uint256, CDataStream*> mapOrphanTransactions;41 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;42 43-map<uint256, CWalletTx> mapWallet;44-vector<uint256> vWalletUpdated;45-CCriticalSection cs_mapWallet;46-47-map<vector<unsigned char>, CPrivKey> mapKeys;48-map<uint160, vector<unsigned char> > mapPubKeys;49-CCriticalSection cs_mapKeys;50-CKey keyUser;51-52-map<uint256, int> mapRequestCount;53-CCriticalSection cs_mapRequestCount;54-55-map<string, string> mapAddressBook;56-CCriticalSection cs_mapAddressBook;57-58-vector<unsigned char> vchDefaultKey;59 60 double dHashesPerSec;61 int64 nHPSTimerStart;62@@ -77,151 +74,82 @@63 64 //////////////////////////////////////////////////////////////////////////////65 //66-// mapKeys67+// dispatching functions68 //69 70-bool AddKey(const CKey& key)71-{72- CRITICAL_BLOCK(cs_mapKeys)73- {74- mapKeys[key.GetPubKey()] = key.GetPrivKey();75- mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();76- }77- return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());78-}79-80-vector<unsigned char> GenerateNewKey()81-{82- RandAddSeedPerfmon();83- CKey key;84- key.MakeNewKey();85- if (!AddKey(key))86- throw runtime_error("GenerateNewKey() : AddKey failed");87- return key.GetPubKey();88-}89-90-91-92-93-//////////////////////////////////////////////////////////////////////////////94-//95-// mapWallet96-//97-98-bool AddToWallet(const CWalletTx& wtxIn)99-{100- uint256 hash = wtxIn.GetHash();101- CRITICAL_BLOCK(cs_mapWallet)102- {103- // Inserts only if not already there, returns tx inserted or tx found104- pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));105- CWalletTx& wtx = (*ret.first).second;106- bool fInsertedNew = ret.second;107- if (fInsertedNew)108- wtx.nTimeReceived = GetAdjustedTime();109-110- bool fUpdated = false;111- if (!fInsertedNew)112- {113- // Merge114- if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)115- {116- wtx.hashBlock = wtxIn.hashBlock;117- fUpdated = true;118- }119- if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))120- {121- wtx.vMerkleBranch = wtxIn.vMerkleBranch;122- wtx.nIndex = wtxIn.nIndex;123- fUpdated = true;124- }125- if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)126- {127- wtx.fFromMe = wtxIn.fFromMe;128- fUpdated = true;129- }130- fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);131- }132-133- //// debug print134- printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));135-136- // Write to disk137- if (fInsertedNew || fUpdated)138- if (!wtx.WriteToDisk())139- return false;140-141- // If default receiving address gets used, replace it with a new one142- CScript scriptDefaultKey;143- scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);144- BOOST_FOREACH(const CTxOut& txout, wtx.vout)145- {146- if (txout.scriptPubKey == scriptDefaultKey)147- {148- CWalletDB walletdb;149- vchDefaultKey = GetKeyFromKeyPool();150- walletdb.WriteDefaultKey(vchDefaultKey);151- walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");152- }153- }154-155- // Notify UI156- vWalletUpdated.push_back(hash);157- }158-159- // Refresh UI160- MainFrameRepaint();161- return true;162-}163-164-bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false)165-{166- uint256 hash = tx.GetHash();167- bool fExisted = mapWallet.count(hash);168- if (fExisted && !fUpdate) return false;169- if (fExisted || tx.IsMine() || tx.IsFromMe())170- {171- CWalletTx wtx(tx);172- // Get merkle branch if transaction was found in a block173- if (pblock)174- wtx.SetMerkleBranch(pblock);175- return AddToWallet(wtx);176- }177+void RegisterWallet(CWallet* pwalletIn)178+{179+ CRITICAL_BLOCK(cs_setpwalletRegistered)180+ {181+ setpwalletRegistered.insert(pwalletIn);182+ }183+}184+185+void UnregisterWallet(CWallet* pwalletIn)186+{187+ CRITICAL_BLOCK(cs_setpwalletRegistered)188+ {189+ setpwalletRegistered.erase(pwalletIn);190+ }191+}192+193+bool static IsFromMe(CTransaction& tx)194+{195+ BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)196+ if (pwallet->IsFromMe(tx))197+ return true;198 return false;199 }200 201-bool EraseFromWallet(uint256 hash)202-{203- CRITICAL_BLOCK(cs_mapWallet)204- {205- if (mapWallet.erase(hash))206- CWalletDB().EraseTx(hash);207- }208- return true;209-}210-211-void WalletUpdateSpent(const COutPoint& prevout)212-{213- // Anytime a signature is successfully verified, it's proof the outpoint is spent.214- // Update the wallet spent flag if it doesn't know due to wallet.dat being215- // restored from backup or the user making copies of wallet.dat.216- CRITICAL_BLOCK(cs_mapWallet)217- {218- map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);219- if (mi != mapWallet.end())220- {221- CWalletTx& wtx = (*mi).second;222- if (!wtx.IsSpent(prevout.n) && wtx.vout[prevout.n].IsMine())223- {224- printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());225- wtx.MarkSpent(prevout.n);226- wtx.WriteToDisk();227- vWalletUpdated.push_back(prevout.hash);228- }229- }230- }231-}232-233+bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)234+{235+ BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)236+ if (pwallet->GetTransaction(hashTx,wtx))237+ return true;238+ return false;239+}240+241+void static EraseFromWallets(uint256 hash)242+{243+ BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)244+ pwallet->EraseFromWallet(hash);245+}246+247+void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)248+{249+ BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)250+ pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);251+}252+253+void static SetBestChain(const CBlockLocator& loc)254+{255+ BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)256+ pwallet->SetBestChain(loc);257+}258+259+void static UpdatedTransaction(const uint256& hashTx)260+{261+ BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)262+ pwallet->UpdatedTransaction(hashTx);263+}264+265+void static PrintWallets(const CBlock& block)266+{267+ BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)268+ pwallet->PrintWallet(block);269+}270+271+void static Inventory(const uint256& hash)272+{273+ BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)274+ pwallet->Inventory(hash);275+}276+277+void static ResendWalletTransactions()278+{279+ BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)280+ pwallet->ResendWalletTransactions();281+}282 283 284 285@@ -234,7 +162,7 @@286 // mapOrphanTransactions287 //288 289-void AddOrphanTx(const CDataStream& vMsg)290+void static AddOrphanTx(const CDataStream& vMsg)291 {292 CTransaction tx;293 CDataStream(vMsg) >> tx;294@@ -246,7 +174,7 @@295 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));296 }297 298-void EraseOrphanTx(uint256 hash)299+void static EraseOrphanTx(uint256 hash)300 {301 if (!mapOrphanTransactions.count(hash))302 return;303@@ -306,190 +234,6 @@304 CTxDB txdb("r");305 CTxIndex txindex;306 return ReadFromDisk(txdb, prevout, txindex);307-}308-309-bool CTxIn::IsMine() const310-{311- CRITICAL_BLOCK(cs_mapWallet)312- {313- map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);314- if (mi != mapWallet.end())315- {316- const CWalletTx& prev = (*mi).second;317- if (prevout.n < prev.vout.size())318- if (prev.vout[prevout.n].IsMine())319- return true;320- }321- }322- return false;323-}324-325-int64 CTxIn::GetDebit() const326-{327- CRITICAL_BLOCK(cs_mapWallet)328- {329- map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);330- if (mi != mapWallet.end())331- {332- const CWalletTx& prev = (*mi).second;333- if (prevout.n < prev.vout.size())334- if (prev.vout[prevout.n].IsMine())335- return prev.vout[prevout.n].nValue;336- }337- }338- return 0;339-}340-341-int64 CWalletTx::GetTxTime() const342-{343- if (!fTimeReceivedIsTxTime && hashBlock != 0)344- {345- // If we did not receive the transaction directly, we rely on the block's346- // time to figure out when it happened. We use the median over a range347- // of blocks to try to filter out inaccurate block times.348- map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);349- if (mi != mapBlockIndex.end())350- {351- CBlockIndex* pindex = (*mi).second;352- if (pindex)353- return pindex->GetMedianTime();354- }355- }356- return nTimeReceived;357-}358-359-int CWalletTx::GetRequestCount() const360-{361- // Returns -1 if it wasn't being tracked362- int nRequests = -1;363- CRITICAL_BLOCK(cs_mapRequestCount)364- {365- if (IsCoinBase())366- {367- // Generated block368- if (hashBlock != 0)369- {370- map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);371- if (mi != mapRequestCount.end())372- nRequests = (*mi).second;373- }374- }375- else376- {377- // Did anyone request this transaction?378- map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());379- if (mi != mapRequestCount.end())380- {381- nRequests = (*mi).second;382-383- // How about the block it's in?384- if (nRequests == 0 && hashBlock != 0)385- {386- map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);387- if (mi != mapRequestCount.end())388- nRequests = (*mi).second;389- else390- nRequests = 1; // If it's in someone else's block it must have got out391- }392- }393- }394- }395- return nRequests;396-}397-398-void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string, int64> >& listReceived,399- list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const400-{401- nGeneratedImmature = nGeneratedMature = nFee = 0;402- listReceived.clear();403- listSent.clear();404- strSentAccount = strFromAccount;405-406- if (IsCoinBase())407- {408- if (GetBlocksToMaturity() > 0)409- nGeneratedImmature = CTransaction::GetCredit();410- else411- nGeneratedMature = GetCredit();412- return;413- }414-415- // Compute fee:416- int64 nDebit = GetDebit();417- if (nDebit > 0) // debit>0 means we signed/sent this transaction418- {419- int64 nValueOut = GetValueOut();420- nFee = nDebit - nValueOut;421- }422-423- // Sent/received. Standard client will never generate a send-to-multiple-recipients,424- // but non-standard clients might (so return a list of address/amount pairs)425- BOOST_FOREACH(const CTxOut& txout, vout)426- {427- string address;428- uint160 hash160;429- vector<unsigned char> vchPubKey;430- if (ExtractHash160(txout.scriptPubKey, hash160))431- address = Hash160ToAddress(hash160);432- else if (ExtractPubKey(txout.scriptPubKey, false, vchPubKey))433- address = PubKeyToAddress(vchPubKey);434- else435- {436- printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",437- this->GetHash().ToString().c_str());438- address = " unknown ";439- }440-441- // Don't report 'change' txouts442- if (nDebit > 0 && txout.IsChange())443- continue;444-445- if (nDebit > 0)446- listSent.push_back(make_pair(address, txout.nValue));447-448- if (txout.IsMine())449- listReceived.push_back(make_pair(address, txout.nValue));450- }451-452-}453-454-void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived, 455- int64& nSent, int64& nFee) const456-{457- nGenerated = nReceived = nSent = nFee = 0;458-459- int64 allGeneratedImmature, allGeneratedMature, allFee;460- allGeneratedImmature = allGeneratedMature = allFee = 0;461- string strSentAccount;462- list<pair<string, int64> > listReceived;463- list<pair<string, int64> > listSent;464- GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);465-466- if (strAccount == "")467- nGenerated = allGeneratedMature;468- if (strAccount == strSentAccount)469- {470- BOOST_FOREACH(const PAIRTYPE(string,int64)& s, listSent)471- nSent += s.second;472- nFee = allFee;473- }474- CRITICAL_BLOCK(cs_mapAddressBook)475- {476- BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)477- {478- if (mapAddressBook.count(r.first))479- {480- if (mapAddressBook[r.first] == strAccount)481- {482- nReceived += r.second;483- }484- }485- else if (strAccount.empty())486- {487- nReceived += r.second;488- }489- }490- }491 }492 493 494@@ -544,69 +288,6 @@495 496 return pindexBest->nHeight - pindex->nHeight + 1;497 }498-499-500-501-void CWalletTx::AddSupportingTransactions(CTxDB& txdb)502-{503- vtxPrev.clear();504-505- const int COPY_DEPTH = 3;506- if (SetMerkleBranch() < COPY_DEPTH)507- {508- vector<uint256> vWorkQueue;509- BOOST_FOREACH(const CTxIn& txin, vin)510- vWorkQueue.push_back(txin.prevout.hash);511-512- // This critsect is OK because txdb is already open513- CRITICAL_BLOCK(cs_mapWallet)514- {515- map<uint256, const CMerkleTx*> mapWalletPrev;516- set<uint256> setAlreadyDone;517- for (int i = 0; i < vWorkQueue.size(); i++)518- {519- uint256 hash = vWorkQueue[i];520- if (setAlreadyDone.count(hash))521- continue;522- setAlreadyDone.insert(hash);523-524- CMerkleTx tx;525- if (mapWallet.count(hash))526- {527- tx = mapWallet[hash];528- BOOST_FOREACH(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)529- mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;530- }531- else if (mapWalletPrev.count(hash))532- {533- tx = *mapWalletPrev[hash];534- }535- else if (!fClient && txdb.ReadDiskTx(hash, tx))536- {537- ;538- }539- else540- {541- printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");542- continue;543- }544-545- int nDepth = tx.SetMerkleBranch();546- vtxPrev.push_back(tx);547-548- if (nDepth < COPY_DEPTH)549- BOOST_FOREACH(const CTxIn& txin, tx.vin)550- vWorkQueue.push_back(txin.prevout.hash);551- }552- }553- }554-555- reverse(vtxPrev.begin(), vtxPrev.end());556-}557-558-559-560-561 562 563 564@@ -751,7 +432,7 @@565 nLastTime = nNow;566 // -limitfreerelay unit is thousand-bytes-per-minute567 // At default rate it would take over a month to fill 1GB568- if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe())569+ if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))570 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");571 if (fDebug)572 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);573@@ -774,12 +455,17 @@574 ///// are we sure this is ok when loading transactions or restoring block txes575 // If updated, erase old tx from wallet576 if (ptxOld)577- EraseFromWallet(ptxOld->GetHash());578+ EraseFromWallets(ptxOld->GetHash());579 580 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());581 return true;582 }583 584+bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)585+{586+ CTxDB txdb("r");587+ return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);588+}589 590 bool CTransaction::AddToMemoryPoolUnchecked()591 {592@@ -863,6 +549,12 @@593 }594 }595 596+bool CMerkleTx::AcceptToMemoryPool()597+{598+ CTxDB txdb("r");599+ return AcceptToMemoryPool(txdb);600+}601+602 603 604 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)605@@ -884,148 +576,10 @@606 return false;607 }608 609-int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)610-{611- int ret = 0;612-613- CBlockIndex* pindex = pindexStart;614- CRITICAL_BLOCK(cs_mapWallet)615- {616- while (pindex)617- {618- CBlock block;619- block.ReadFromDisk(pindex, true);620- BOOST_FOREACH(CTransaction& tx, block.vtx)621- {622- if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))623- ret++;624- }625- pindex = pindex->pnext;626- }627- }628- return ret;629-}630-631-void ReacceptWalletTransactions()632+bool CWalletTx::AcceptWalletTransaction() 633 {634 CTxDB txdb("r");635- bool fRepeat = true;636- while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)637- {638- fRepeat = false;639- vector<CDiskTxPos> vMissingTx;640- BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)641- {642- CWalletTx& wtx = item.second;643- if (wtx.IsCoinBase() && wtx.IsSpent(0))644- continue;645-646- CTxIndex txindex;647- bool fUpdated = false;648- if (txdb.ReadTxIndex(wtx.GetHash(), txindex))649- {650- // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat651- if (txindex.vSpent.size() != wtx.vout.size())652- {653- printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());654- continue;655- }656- for (int i = 0; i < txindex.vSpent.size(); i++)657- {658- if (wtx.IsSpent(i))659- continue;660- if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())661- {662- wtx.MarkSpent(i);663- fUpdated = true;664- vMissingTx.push_back(txindex.vSpent[i]);665- }666- }667- if (fUpdated)668- {669- printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());670- wtx.MarkDirty();671- wtx.WriteToDisk();672- }673- }674- else675- {676- // Reaccept any txes of ours that aren't already in a block677- if (!wtx.IsCoinBase())678- wtx.AcceptWalletTransaction(txdb, false);679- }680- }681- if (!vMissingTx.empty())682- {683- // TODO: optimize this to scan just part of the block chain?684- if (ScanForWalletTransactions(pindexGenesisBlock))685- fRepeat = true; // Found missing transactions: re-do Reaccept.686- }687- }688-}689-690-691-void CWalletTx::RelayWalletTransaction(CTxDB& txdb)692-{693- BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)694- {695- if (!tx.IsCoinBase())696- {697- uint256 hash = tx.GetHash();698- if (!txdb.ContainsTx(hash))699- RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);700- }701- }702- if (!IsCoinBase())703- {704- uint256 hash = GetHash();705- if (!txdb.ContainsTx(hash))706- {707- printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());708- RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);709- }710- }711-}712-713-void ResendWalletTransactions()714-{715- // Do this infrequently and randomly to avoid giving away716- // that these are our transactions.717- static int64 nNextTime;718- if (GetTime() < nNextTime)719- return;720- bool fFirst = (nNextTime == 0);721- nNextTime = GetTime() + GetRand(30 * 60);722- if (fFirst)723- return;724-725- // Only do it if there's been a new block since last time726- static int64 nLastTime;727- if (nTimeBestReceived < nLastTime)728- return;729- nLastTime = GetTime();730-731- // Rebroadcast any of our txes that aren't in a block yet732- printf("ResendWalletTransactions()\n");733- CTxDB txdb("r");734- CRITICAL_BLOCK(cs_mapWallet)735- {736- // Sort them in chronological order737- multimap<unsigned int, CWalletTx*> mapSorted;738- BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)739- {740- CWalletTx& wtx = item.second;741- // Don't rebroadcast until it's had plenty of time that742- // it should have gotten in already by now.743- if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)744- mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));745- }746- BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)747- {748- CWalletTx& wtx = *item.second;749- wtx.RelayWalletTransaction(txdb);750- }751- }752+ return AcceptWalletTransaction(txdb);753 }754 755 int CTxIndex::GetDepthInMainChain() const756@@ -1072,7 +626,7 @@757 return true;758 }759 760-uint256 GetOrphanRoot(const CBlock* pblock)761+uint256 static GetOrphanRoot(const CBlock* pblock)762 {763 // Work back to the first block in the orphan chain764 while (mapOrphanBlocks.count(pblock->hashPrevBlock))765@@ -1080,7 +634,7 @@766 return pblock->GetHash();767 }768 769-int64 GetBlockValue(int nHeight, int64 nFees)770+int64 static GetBlockValue(int nHeight, int64 nFees)771 {772 int64 nSubsidy = 50 * COIN;773 774@@ -1090,7 +644,7 @@775 return nSubsidy + nFees;776 }777 778-unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)779+unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast)780 {781 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks782 const int64 nTargetSpacing = 10 * 60;783@@ -1152,9 +706,22 @@784 return true;785 }786 787+// Return conservative estimate of total number of blocks, 0 if unknown788+int GetTotalBlocksEstimate()789+{790+ if(fTestNet)791+ {792+ return 0;793+ }794+ else795+ {796+ return nTotalBlocksEstimate;797+ }798+}799+800 bool IsInitialBlockDownload()801 {802- if (pindexBest == NULL || (!fTestNet && nBestHeight < 118000))803+ if (pindexBest == NULL || nBestHeight < (GetTotalBlocksEstimate()-nInitialBlockThreshold))804 return true;805 static int64 nLastUpdate;806 static CBlockIndex* pindexLastBest;807@@ -1167,7 +734,7 @@808 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);809 }810 811-void InvalidChainFound(CBlockIndex* pindexNew)812+void static InvalidChainFound(CBlockIndex* pindexNew)813 {814 if (pindexNew->bnChainWork > bnBestInvalidWork)815 {816@@ -1443,12 +1010,12 @@817 818 // Watch for transactions paying to me819 BOOST_FOREACH(CTransaction& tx, vtx)820- AddToWalletIfInvolvingMe(tx, this, true);821+ SyncWithWallets(tx, this, true);822 823 return true;824 }825 826-bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)827+bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)828 {829 printf("REORGANIZE\n");830 831@@ -1586,10 +1153,8 @@832 // Update best block in wallet (so we can detect restored wallets)833 if (!IsInitialBlockDownload())834 {835- CWalletDB walletdb;836 const CBlockLocator locator(pindexNew);837- if (!walletdb.WriteBestBlock(locator))838- return error("SetBestChain() : WriteWalletBest failed");839+ ::SetBestChain(locator);840 }841 842 // New best block843@@ -1643,8 +1208,7 @@844 {845 // Notify UI to display prev block's coinbase if it was ours846 static uint256 hashPrevBestCoinBase;847- CRITICAL_BLOCK(cs_mapWallet)848- vWalletUpdated.push_back(hashPrevBestCoinBase);849+ UpdatedTransaction(hashPrevBestCoinBase);850 hashPrevBestCoinBase = vtx[0].GetHash();851 }852 853@@ -1730,7 +1294,8 @@854 (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||855 (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) ||856 (nHeight == 105000 && hash != uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) ||857- (nHeight == 118000 && hash != uint256("0x000000000000774a7f8a7a12dc906ddb9e17e75d684f15e00f8767f9e8f36553")))858+ (nHeight == 118000 && hash != uint256("0x000000000000774a7f8a7a12dc906ddb9e17e75d684f15e00f8767f9e8f36553")) ||859+ (nHeight == 134444 && hash != uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe")))860 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);861 862 // Write block to history file863@@ -1747,13 +1312,13 @@864 if (hashBestChain == hash)865 CRITICAL_BLOCK(cs_vNodes)866 BOOST_FOREACH(CNode* pnode, vNodes)867- if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 118000))868+ if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 134444))869 pnode->PushInventory(CInv(MSG_BLOCK, hash));870 871 return true;872 }873 874-bool ProcessBlock(CNode* pfrom, CBlock* pblock)875+bool static ProcessBlock(CNode* pfrom, CBlock* pblock)876 {877 // Check for duplicate878 uint256 hash = pblock->GetHash();879@@ -1815,7 +1380,7 @@880 881 882 template<typename Stream>883-bool ScanMessageStart(Stream& s)884+bool static ScanMessageStart(Stream& s)885 {886 // Scan ahead to the next pchMessageStart, which should normally be immediately887 // at the file pointer. Leaves file pointer at end of pchMessageStart.888@@ -2030,7 +1595,7 @@889 for (int i = 0; i < nCol; i++)890 printf("| ");891 printf("|\n");892- }893+ }894 nPrevCol = nCol;895 896 // print columns897@@ -2048,16 +1613,7 @@898 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),899 block.vtx.size());900 901- CRITICAL_BLOCK(cs_mapWallet)902- {903- if (mapWallet.count(block.vtx[0].GetHash()))904- {905- CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];906- printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());907- }908- }909- printf("\n");910-911+ PrintWallets(block);912 913 // put the main timechain first914 vector<CBlockIndex*>& vNext = mapNext[pindex];915@@ -2197,7 +1753,7 @@916 //917 918 919-bool AlreadyHave(CTxDB& txdb, const CInv& inv)920+bool static AlreadyHave(CTxDB& txdb, const CInv& inv)921 {922 switch (inv.type)923 {924@@ -2217,128 +1773,7 @@925 char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };926 927 928-bool ProcessMessages(CNode* pfrom)929-{930- CDataStream& vRecv = pfrom->vRecv;931- if (vRecv.empty())932- return true;933- //if (fDebug)934- // printf("ProcessMessages(%u bytes)\n", vRecv.size());935-936- //937- // Message format938- // (4) message start939- // (12) command940- // (4) size941- // (4) checksum942- // (x) data943- //944-945- loop946- {947- // Scan for message start948- CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));949- int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());950- if (vRecv.end() - pstart < nHeaderSize)951- {952- if (vRecv.size() > nHeaderSize)953- {954- printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");955- vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);956- }957- break;958- }959- if (pstart - vRecv.begin() > 0)960- printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());961- vRecv.erase(vRecv.begin(), pstart);962-963- // Read header964- vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);965- CMessageHeader hdr;966- vRecv >> hdr;967- if (!hdr.IsValid())968- {969- printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());970- continue;971- }972- string strCommand = hdr.GetCommand();973-974- // Message size975- unsigned int nMessageSize = hdr.nMessageSize;976- if (nMessageSize > MAX_SIZE)977- {978- printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);979- continue;980- }981- if (nMessageSize > vRecv.size())982- {983- // Rewind and wait for rest of message984- vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());985- break;986- }987-988- // Checksum989- if (vRecv.GetVersion() >= 209)990- {991- uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);992- unsigned int nChecksum = 0;993- memcpy(&nChecksum, &hash, sizeof(nChecksum));994- if (nChecksum != hdr.nChecksum)995- {996- printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",997- strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);998- continue;999- }1000- }1001-1002- // Copy message to its own buffer1003- CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);1004- vRecv.ignore(nMessageSize);1005-1006- // Process message1007- bool fRet = false;1008- try1009- {1010- CRITICAL_BLOCK(cs_main)1011- fRet = ProcessMessage(pfrom, strCommand, vMsg);1012- if (fShutdown)1013- return true;1014- }1015- catch (std::ios_base::failure& e)1016- {1017- if (strstr(e.what(), "end of data"))1018- {1019- // Allow exceptions from underlength message on vRecv1020- printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());1021- }1022- else if (strstr(e.what(), "size too large"))1023- {1024- // Allow exceptions from overlong size1025- printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());1026- }1027- else1028- {1029- PrintExceptionContinue(&e, "ProcessMessage()");1030- }1031- }1032- catch (std::exception& e) {1033- PrintExceptionContinue(&e, "ProcessMessage()");1034- } catch (...) {1035- PrintExceptionContinue(NULL, "ProcessMessage()");1036- }1037-1038- if (!fRet)1039- printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);1040- }1041-1042- vRecv.Compact();1043- return true;1044-}1045-1046-1047-1048-1049-bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)1050+bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)1051 {1052 static map<unsigned int, vector<unsigned char> > mapReuseKey;1053 RandAddSeedPerfmon();1054@@ -2535,12 +1970,7 @@1055 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));1056 1057 // Track requests for our stuff1058- CRITICAL_BLOCK(cs_mapRequestCount)1059- {1060- map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);1061- if (mi != mapRequestCount.end())1062- (*mi).second++;1063- }1064+ Inventory(inv.hash);1065 }1066 }1067 1068@@ -2593,12 +2023,7 @@1069 }1070 1071 // Track requests for our stuff1072- CRITICAL_BLOCK(cs_mapRequestCount)1073- {1074- map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);1075- if (mi != mapRequestCount.end())1076- (*mi).second++;1077- }1078+ Inventory(inv.hash);1079 }1080 }1081 1082@@ -2616,20 +2041,24 @@1083 if (pindex)1084 pindex = pindex->pnext;1085 int nLimit = 500 + locator.GetDistanceBack();1086+ unsigned int nBytes = 0;1087 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);1088 for (; pindex; pindex = pindex->pnext)1089 {1090 if (pindex->GetBlockHash() == hashStop)1091 {1092- printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());1093+ printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);1094 break;1095 }1096 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));1097- if (--nLimit <= 0)1098+ CBlock block;1099+ block.ReadFromDisk(pindex, true);1100+ nBytes += block.GetSerializeSize(SER_NETWORK);1101+ if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)1102 {1103 // When this block is requested, we'll send an inv that'll make them1104 // getblocks the next batch of inventory.1105- printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());1106+ printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);1107 pfrom->hashContinue = pindex->GetBlockHash();1108 break;1109 }1110@@ -2686,7 +2115,7 @@1111 bool fMissingInputs = false;1112 if (tx.AcceptToMemoryPool(true, &fMissingInputs))1113 {1114- AddToWalletIfInvolvingMe(tx, NULL, true);1115+ SyncWithWallets(tx, NULL, true);1116 RelayMessage(inv, vMsg);1117 mapAlreadyAskedFor.erase(inv);1118 vWorkQueue.push_back(inv.hash);1119@@ -2707,7 +2136,7 @@1120 if (tx.AcceptToMemoryPool(true))1121 {1122 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());1123- AddToWalletIfInvolvingMe(tx, NULL, true);1124+ SyncWithWallets(tx, NULL, true);1125 RelayMessage(inv, vMsg);1126 mapAlreadyAskedFor.erase(inv);1127 vWorkQueue.push_back(inv.hash);1128@@ -2784,43 +2213,12 @@1129 1130 // Keep giving the same key to the same ip until they use it1131 if (!mapReuseKey.count(pfrom->addr.ip))1132- mapReuseKey[pfrom->addr.ip] = GetKeyFromKeyPool();1133+ mapReuseKey[pfrom->addr.ip] = pwalletMain->GetKeyFromKeyPool();1134 1135 // Send back approval of order and pubkey to use1136 CScript scriptPubKey;1137 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;1138 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);1139- }1140-1141-1142- else if (strCommand == "submitorder")1143- {1144- uint256 hashReply;1145- vRecv >> hashReply;1146-1147- if (!GetBoolArg("-allowreceivebyip"))1148- {1149- pfrom->PushMessage("reply", hashReply, (int)2);1150- return true;1151- }1152-1153- CWalletTx wtxNew;1154- vRecv >> wtxNew;1155- wtxNew.fFromMe = false;1156-1157- // Broadcast1158- if (!wtxNew.AcceptWalletTransaction())1159- {1160- pfrom->PushMessage("reply", hashReply, (int)1);1161- return error("submitorder AcceptWalletTransaction() failed, returning error 1");1162- }1163- wtxNew.fTimeReceivedIsTxTime = true;1164- AddToWallet(wtxNew);1165- wtxNew.RelayWalletTransaction();1166- mapReuseKey.erase(pfrom->addr.ip);1167-1168- // Send back confirmation1169- pfrom->PushMessage("reply", hashReply, (int)0);1170 }1171 1172 1173@@ -2880,12 +2278,123 @@1174 return true;1175 }1176 1177-1178-1179-1180-1181-1182-1183+bool ProcessMessages(CNode* pfrom)1184+{1185+ CDataStream& vRecv = pfrom->vRecv;1186+ if (vRecv.empty())1187+ return true;1188+ //if (fDebug)1189+ // printf("ProcessMessages(%u bytes)\n", vRecv.size());1190+1191+ //1192+ // Message format1193+ // (4) message start1194+ // (12) command1195+ // (4) size1196+ // (4) checksum1197+ // (x) data1198+ //1199+1200+ loop1201+ {1202+ // Scan for message start1203+ CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));1204+ int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());1205+ if (vRecv.end() - pstart < nHeaderSize)1206+ {1207+ if (vRecv.size() > nHeaderSize)1208+ {1209+ printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");1210+ vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);1211+ }1212+ break;1213+ }1214+ if (pstart - vRecv.begin() > 0)1215+ printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());1216+ vRecv.erase(vRecv.begin(), pstart);1217+1218+ // Read header1219+ vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);1220+ CMessageHeader hdr;1221+ vRecv >> hdr;1222+ if (!hdr.IsValid())1223+ {1224+ printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());1225+ continue;1226+ }1227+ string strCommand = hdr.GetCommand();1228+1229+ // Message size1230+ unsigned int nMessageSize = hdr.nMessageSize;1231+ if (nMessageSize > MAX_SIZE)1232+ {1233+ printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);1234+ continue;1235+ }1236+ if (nMessageSize > vRecv.size())1237+ {1238+ // Rewind and wait for rest of message1239+ vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());1240+ break;1241+ }1242+1243+ // Checksum1244+ if (vRecv.GetVersion() >= 209)1245+ {1246+ uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);1247+ unsigned int nChecksum = 0;1248+ memcpy(&nChecksum, &hash, sizeof(nChecksum));1249+ if (nChecksum != hdr.nChecksum)1250+ {1251+ printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",1252+ strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);1253+ continue;1254+ }1255+ }1256+1257+ // Copy message to its own buffer1258+ CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);1259+ vRecv.ignore(nMessageSize);1260+1261+ // Process message1262+ bool fRet = false;1263+ try1264+ {1265+ CRITICAL_BLOCK(cs_main)1266+ fRet = ProcessMessage(pfrom, strCommand, vMsg);1267+ if (fShutdown)1268+ return true;1269+ }1270+ catch (std::ios_base::failure& e)1271+ {1272+ if (strstr(e.what(), "end of data"))1273+ {1274+ // Allow exceptions from underlength message on vRecv1275+ printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());1276+ }1277+ else if (strstr(e.what(), "size too large"))1278+ {1279+ // Allow exceptions from overlong size1280+ printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());1281+ }1282+ else1283+ {1284+ PrintExceptionContinue(&e, "ProcessMessage()");1285+ }1286+ }1287+ catch (std::exception& e) {1288+ PrintExceptionContinue(&e, "ProcessMessage()");1289+ } catch (...) {1290+ PrintExceptionContinue(NULL, "ProcessMessage()");1291+ }1292+1293+ if (!fRet)1294+ printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);1295+ }1296+1297+ vRecv.Compact();1298+ return true;1299+}1300 1301 1302 bool SendMessages(CNode* pto, bool fSendTrickle)1303@@ -3010,16 +2519,10 @@1304 // always trickle our own transactions1305 if (!fTrickleWait)1306 {1307- TRY_CRITICAL_BLOCK(cs_mapWallet)1308- {1309- map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);1310- if (mi != mapWallet.end())1311- {1312- CWalletTx& wtx = (*mi).second;1313- if (wtx.fFromMe)1314- fTrickleWait = true;1315- }1316- }1317+ CWalletTx wtx;1318+ if (GetTransaction(inv.hash, wtx))1319+ if (wtx.fFromMe)1320+ fTrickleWait = true;1321 }1322 1323 if (fTrickleWait)1324@@ -3092,57 +2595,7 @@1325 // BitcoinMiner1326 //1327 1328-void GenerateBitcoins(bool fGenerate)1329-{1330- if (fGenerateBitcoins != fGenerate)1331- {1332- fGenerateBitcoins = fGenerate;1333- CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);1334- MainFrameRepaint();1335- }1336- if (fGenerateBitcoins)1337- {1338- int nProcessors = boost::thread::hardware_concurrency();1339- printf("%d processors\n", nProcessors);1340- if (nProcessors < 1)1341- nProcessors = 1;1342- if (fLimitProcessors && nProcessors > nLimitProcessors)1343- nProcessors = nLimitProcessors;1344- int nAddThreads = nProcessors - vnThreadsRunning[3];1345- printf("Starting %d BitcoinMiner threads\n", nAddThreads);1346- for (int i = 0; i < nAddThreads; i++)1347- {1348- if (!CreateThread(ThreadBitcoinMiner, NULL))1349- printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");1350- Sleep(10);1351- }1352- }1353-}1354-1355-void ThreadBitcoinMiner(void* parg)1356-{1357- try1358- {1359- vnThreadsRunning[3]++;1360- BitcoinMiner();1361- vnThreadsRunning[3]--;1362- }1363- catch (std::exception& e) {1364- vnThreadsRunning[3]--;1365- PrintException(&e, "ThreadBitcoinMiner()");1366- } catch (...) {1367- vnThreadsRunning[3]--;1368- PrintException(NULL, "ThreadBitcoinMiner()");1369- }1370- UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));1371- nHPSTimerStart = 0;1372- if (vnThreadsRunning[3] == 0)1373- dHashesPerSec = 0;1374- printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);1375-}1376-1377-1378-int FormatHashBlocks(void* pbuffer, unsigned int len)1379+int static FormatHashBlocks(void* pbuffer, unsigned int len)1380 {1381 unsigned char* pdata = (unsigned char*)pbuffer;1382 unsigned int blocks = 1 + ((len + 8) / 64);1383@@ -3175,7 +2628,7 @@1384 // between calls, but periodically or if nNonce is 0xffff0000 or above,1385 // the block is rebuilt and nNonce starts over at zero.1386 //1387-unsigned int ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)1388+unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)1389 {1390 unsigned int& nNonce = *(unsigned int*)(pdata + 12);1391 for (;;)1392@@ -3432,7 +2885,7 @@1393 }1394 1395 1396-bool CheckWork(CBlock* pblock, CReserveKey& reservekey)1397+bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)1398 {1399 uint256 hash = pblock->GetHash();1400 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();1401@@ -3457,8 +2910,8 @@1402 reservekey.KeepKey();1403 1404 // Track how many getdata requests this block gets1405- CRITICAL_BLOCK(cs_mapRequestCount)1406- mapRequestCount[pblock->GetHash()] = 0;1407+ CRITICAL_BLOCK(wallet.cs_mapRequestCount)1408+ wallet.mapRequestCount[pblock->GetHash()] = 0;1409 1410 // Process this block the same as if we had received it from another node1411 if (!ProcessBlock(NULL, pblock))1412@@ -3469,14 +2922,15 @@1413 return true;1414 }1415 1416-1417-void BitcoinMiner()1418+void static ThreadBitcoinMiner(void* parg);1419+1420+void static BitcoinMiner(CWallet *pwallet)1421 {1422 printf("BitcoinMiner started\n");1423 SetThreadPriority(THREAD_PRIORITY_LOWEST);1424 1425 // Each thread has its own key and counter1426- CReserveKey reservekey;1427+ CReserveKey reservekey(pwallet);1428 unsigned int nExtraNonce = 0;1429 int64 nPrevTime = 0;1430 1431@@ -3552,7 +3006,7 @@1432 assert(hash == pblock->GetHash());1433 1434 SetThreadPriority(THREAD_PRIORITY_NORMAL);1435- CheckWork(pblock.get(), reservekey);1436+ CheckWork(pblock.get(), *pwalletMain, reservekey);1437 SetThreadPriority(THREAD_PRIORITY_LOWEST);1438 break;1439 }1440@@ -3613,422 +3067,54 @@1441 }1442 }1443 1444-1445-1446-1447-1448-1449-1450-1451-1452-1453-1454-1455-1456-1457-1458-1459-1460-1461-//////////////////////////////////////////////////////////////////////////////1462-//1463-// Actions1464-//1465-1466-1467-int64 GetBalance()1468-{1469- int64 nStart = GetTimeMillis();1470-1471- int64 nTotal = 0;1472- CRITICAL_BLOCK(cs_mapWallet)1473- {1474- for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)1475- {1476- CWalletTx* pcoin = &(*it).second;1477- if (!pcoin->IsFinal() || !pcoin->IsConfirmed())1478- continue;1479- nTotal += pcoin->GetAvailableCredit();1480- }1481- }1482-1483- //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);1484- return nTotal;1485-}1486-1487-1488-bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet)1489-{1490- setCoinsRet.clear();1491- nValueRet = 0;1492-1493- // List of values less than target1494- pair<int64, pair<CWalletTx*,unsigned int> > coinLowestLarger;1495- coinLowestLarger.first = INT64_MAX;1496- coinLowestLarger.second.first = NULL;1497- vector<pair<int64, pair<CWalletTx*,unsigned int> > > vValue;1498- int64 nTotalLower = 0;1499-1500- CRITICAL_BLOCK(cs_mapWallet)1501- {1502- vector<CWalletTx*> vCoins;1503- vCoins.reserve(mapWallet.size());1504- for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)1505- vCoins.push_back(&(*it).second);1506- random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);1507-1508- BOOST_FOREACH(CWalletTx* pcoin, vCoins)1509- {1510- if (!pcoin->IsFinal() || !pcoin->IsConfirmed())1511- continue;1512-1513- if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)1514- continue;1515-1516- int nDepth = pcoin->GetDepthInMainChain();1517- if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))1518- continue;1519-1520- for (int i = 0; i < pcoin->vout.size(); i++)1521- {1522- if (pcoin->IsSpent(i) || !pcoin->vout[i].IsMine())1523- continue;1524-1525- int64 n = pcoin->vout[i].nValue;1526-1527- if (n <= 0)1528- continue;1529-1530- pair<int64,pair<CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));1531-1532- if (n == nTargetValue)1533- {1534- setCoinsRet.insert(coin.second);1535- nValueRet += coin.first;1536- return true;1537- }1538- else if (n < nTargetValue + CENT)1539- {1540- vValue.push_back(coin);1541- nTotalLower += n;1542- }1543- else if (n < coinLowestLarger.first)1544- {1545- coinLowestLarger = coin;1546- }1547- }1548- }1549- }1550-1551- if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)1552- {1553- for (int i = 0; i < vValue.size(); ++i)1554- {1555- setCoinsRet.insert(vValue[i].second);1556- nValueRet += vValue[i].first;1557- }1558- return true;1559- }1560-1561- if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))1562- {1563- if (coinLowestLarger.second.first == NULL)1564- return false;1565- setCoinsRet.insert(coinLowestLarger.second);1566- nValueRet += coinLowestLarger.first;1567- return true;1568- }1569-1570- if (nTotalLower >= nTargetValue + CENT)1571- nTargetValue += CENT;1572-1573- // Solve subset sum by stochastic approximation1574- sort(vValue.rbegin(), vValue.rend());1575- vector<char> vfIncluded;1576- vector<char> vfBest(vValue.size(), true);1577- int64 nBest = nTotalLower;1578-1579- for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)1580- {1581- vfIncluded.assign(vValue.size(), false);1582- int64 nTotal = 0;1583- bool fReachedTarget = false;1584- for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)1585- {1586- for (int i = 0; i < vValue.size(); i++)1587- {1588- if (nPass == 0 ? rand() % 2 : !vfIncluded[i])1589- {1590- nTotal += vValue[i].first;1591- vfIncluded[i] = true;1592- if (nTotal >= nTargetValue)1593- {1594- fReachedTarget = true;1595- if (nTotal < nBest)1596- {1597- nBest = nTotal;1598- vfBest = vfIncluded;1599- }1600- nTotal -= vValue[i].first;1601- vfIncluded[i] = false;1602- }1603- }1604- }1605- }1606- }1607-1608- // If the next larger is still closer, return it1609- if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)1610- {1611- setCoinsRet.insert(coinLowestLarger.second);1612- nValueRet += coinLowestLarger.first;1613- }1614- else {1615- for (int i = 0; i < vValue.size(); i++)1616- if (vfBest[i])1617- {1618- setCoinsRet.insert(vValue[i].second);1619- nValueRet += vValue[i].first;1620- }1621-1622- //// debug print1623- printf("SelectCoins() best subset: ");1624- for (int i = 0; i < vValue.size(); i++)1625- if (vfBest[i])1626- printf("%s ", FormatMoney(vValue[i].first).c_str());1627- printf("total %s\n", FormatMoney(nBest).c_str());1628- }1629-1630- return true;1631-}1632-1633-bool SelectCoins(int64 nTargetValue, set<pair<CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet)1634-{1635- return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||1636- SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||1637- SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));1638-}1639-1640-1641-1642-1643-bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)1644-{1645- int64 nValue = 0;1646- BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)1647- {1648- if (nValue < 0)1649- return false;1650- nValue += s.second;1651- }1652- if (vecSend.empty() || nValue < 0)1653- return false;1654-1655- CRITICAL_BLOCK(cs_main)1656- {1657- // txdb must be opened before the mapWallet lock1658- CTxDB txdb("r");1659- CRITICAL_BLOCK(cs_mapWallet)1660- {1661- nFeeRet = nTransactionFee;1662- loop1663- {1664- wtxNew.vin.clear();1665- wtxNew.vout.clear();1666- wtxNew.fFromMe = true;1667-1668- int64 nTotalValue = nValue + nFeeRet;1669- double dPriority = 0;1670- // vouts to the payees1671- BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)1672- wtxNew.vout.push_back(CTxOut(s.second, s.first));1673-1674- // Choose coins to use1675- set<pair<CWalletTx*,unsigned int> > setCoins;1676- int64 nValueIn = 0;1677- if (!SelectCoins(nTotalValue, setCoins, nValueIn))1678- return false;1679- BOOST_FOREACH(PAIRTYPE(CWalletTx*, unsigned int) pcoin, setCoins)1680- {1681- int64 nCredit = pcoin.first->vout[pcoin.second].nValue;1682- dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();1683- }1684-1685- int64 nChange = nValueIn - nValue - nFeeRet;1686-1687- // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE1688- // or until nChange becomes zero1689- if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)1690- {1691- int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);1692- nChange -= nMoveToFee;1693- nFeeRet += nMoveToFee;1694- }1695-1696- if (nChange > 0)1697- {1698- // Note: We use a new key here to keep it from being obvious which side is the change.1699- // The drawback is that by not reusing a previous key, the change may be lost if a1700- // backup is restored, if the backup doesn't have the new private key for the change.1701- // If we reused the old key, it would be possible to add code to look for and1702- // rediscover unknown transactions that were written with keys of ours to recover1703- // post-backup change.1704-1705- // Reserve a new key pair from key pool1706- vector<unsigned char> vchPubKey = reservekey.GetReservedKey();1707- assert(mapKeys.count(vchPubKey));1708-1709- // Fill a vout to ourself, using same address type as the payment1710- CScript scriptChange;1711- if (vecSend[0].first.GetBitcoinAddressHash160() != 0)1712- scriptChange.SetBitcoinAddress(vchPubKey);1713- else1714- scriptChange << vchPubKey << OP_CHECKSIG;1715-1716- // Insert change txn at random position:1717- vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());1718- wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));1719- }1720- else1721- reservekey.ReturnKey();1722-1723- // Fill vin1724- BOOST_FOREACH(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)1725- wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));1726-1727- // Sign1728- int nIn = 0;1729- BOOST_FOREACH(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)1730- if (!SignSignature(*coin.first, wtxNew, nIn++))1731- return false;1732-1733- // Limit size1734- unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);1735- if (nBytes >= MAX_BLOCK_SIZE_GEN/5)1736- return false;1737- dPriority /= nBytes;1738-1739- // Check that enough fee is included1740- int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);1741- bool fAllowFree = CTransaction::AllowFree(dPriority);1742- int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);1743- if (nFeeRet < max(nPayFee, nMinFee))1744- {1745- nFeeRet = max(nPayFee, nMinFee);1746- continue;1747- }1748-1749- // Fill vtxPrev by copying from previous transactions vtxPrev1750- wtxNew.AddSupportingTransactions(txdb);1751- wtxNew.fTimeReceivedIsTxTime = true;1752-1753- break;1754- }1755- }1756- }1757- return true;1758-}1759-1760-bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)1761-{1762- vector< pair<CScript, int64> > vecSend;1763- vecSend.push_back(make_pair(scriptPubKey, nValue));1764- return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);1765-}1766-1767-// Call after CreateTransaction unless you want to abort1768-bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)1769-{1770- CRITICAL_BLOCK(cs_main)1771- {1772- printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());1773- CRITICAL_BLOCK(cs_mapWallet)1774- {1775- // This is only to keep the database open to defeat the auto-flush for the1776- // duration of this scope. This is the only place where this optimization1777- // maybe makes sense; please don't do it anywhere else.1778- CWalletDB walletdb("r");1779-1780- // Take key pair from key pool so it won't be used again1781- reservekey.KeepKey();1782-1783- // Add tx to wallet, because if it has change it's also ours,1784- // otherwise just for transaction history.1785- AddToWallet(wtxNew);1786-1787- // Mark old coins as spent1788- set<CWalletTx*> setCoins;1789- BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)1790- {1791- CWalletTx &pcoin = mapWallet[txin.prevout.hash];1792- pcoin.MarkSpent(txin.prevout.n);1793- pcoin.WriteToDisk();1794- vWalletUpdated.push_back(pcoin.GetHash());1795- }1796- }1797-1798- // Track how many getdata requests our transaction gets1799- CRITICAL_BLOCK(cs_mapRequestCount)1800- mapRequestCount[wtxNew.GetHash()] = 0;1801-1802- // Broadcast1803- if (!wtxNew.AcceptToMemoryPool())1804- {1805- // This must not fail. The transaction has already been signed and recorded.1806- printf("CommitTransaction() : Error: Transaction not valid");1807- return false;1808- }1809- wtxNew.RelayWalletTransaction();1810- }1811- MainFrameRepaint();1812- return true;1813-}1814-1815-1816-1817-1818-// requires cs_main lock1819-string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)1820-{1821- CReserveKey reservekey;1822- int64 nFeeRequired;1823- if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))1824- {1825- string strError;1826- if (nValue + nFeeRequired > GetBalance())1827- 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());1828- else1829- strError = _("Error: Transaction creation failed ");1830- printf("SendMoney() : %s", strError.c_str());1831- return strError;1832- }1833-1834- if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))1835- return "ABORTED";1836-1837- if (!CommitTransaction(wtxNew, reservekey))1838- 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.");1839-1840- MainFrameRepaint();1841- return "";1842-}1843-1844-1845-1846-// requires cs_main lock1847-string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)1848-{1849- // Check amount1850- if (nValue <= 0)1851- return _("Invalid amount");1852- if (nValue + nTransactionFee > GetBalance())1853- return _("Insufficient funds");1854-1855- // Parse bitcoin address1856- CScript scriptPubKey;1857- if (!scriptPubKey.SetBitcoinAddress(strAddress))1858- return _("Invalid bitcoin address");1859-1860- return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);1861-}1862-1863+void static ThreadBitcoinMiner(void* parg)1864+{1865+ CWallet* pwallet = (CWallet*)parg;1866+ try1867+ {1868+ vnThreadsRunning[3]++;1869+ BitcoinMiner(pwallet);1870+ vnThreadsRunning[3]--;1871+ }1872+ catch (std::exception& e) {1873+ vnThreadsRunning[3]--;1874+ PrintException(&e, "ThreadBitcoinMiner()");1875+ } catch (...) {1876+ vnThreadsRunning[3]--;1877+ PrintException(NULL, "ThreadBitcoinMiner()");1878+ }1879+ UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));1880+ nHPSTimerStart = 0;1881+ if (vnThreadsRunning[3] == 0)1882+ dHashesPerSec = 0;1883+ printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);1884+}1885+1886+1887+void GenerateBitcoins(bool fGenerate, CWallet* pwallet)1888+{1889+ if (fGenerateBitcoins != fGenerate)1890+ {1891+ fGenerateBitcoins = fGenerate;1892+ WriteSetting("fGenerateBitcoins", fGenerateBitcoins);1893+ MainFrameRepaint();1894+ }1895+ if (fGenerateBitcoins)1896+ {1897+ int nProcessors = boost::thread::hardware_concurrency();1898+ printf("%d processors\n", nProcessors);1899+ if (nProcessors < 1)1900+ nProcessors = 1;1901+ if (fLimitProcessors && nProcessors > nLimitProcessors)1902+ nProcessors = nLimitProcessors;1903+ int nAddThreads = nProcessors - vnThreadsRunning[3];1904+ printf("Starting %d BitcoinMiner threads\n", nAddThreads);1905+ for (int i = 0; i < nAddThreads; i++)1906+ {1907+ if (!CreateThread(ThreadBitcoinMiner, pwallet))1908+ printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");1909+ Sleep(10);1910+ }1911+ }1912+}1913+
main.h (modified)
1--- v0.3.23/main.h2+++ v0.3.24/main.h3@@ -7,22 +7,25 @@4 #include "bignum.h"5 #include "net.h"6 #include "key.h"7+#include "script.h"8 #include "db.h"9-#include "script.h"10 11 #include <list>12 13-class COutPoint;14-class CInPoint;15-class CDiskTxPos;16-class CCoinBase;17-class CTxIn;18-class CTxOut;19-class CTransaction;20 class CBlock;21 class CBlockIndex;22 class CWalletTx;23+class CWallet;24 class CKeyItem;25+class CReserveKey;26+class CWalletDB;27+28+class CMessageHeader;29+class CAddress;30+class CInv;31+class CRequestTracker;32+class CNode;33+class CBlockIndex;34 35 static const unsigned int MAX_BLOCK_SIZE = 1000000;36 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;37@@ -56,13 +59,11 @@38 extern uint256 hashBestChain;39 extern CBlockIndex* pindexBest;40 extern unsigned int nTransactionsUpdated;41-extern std::map<uint256, int> mapRequestCount;42-extern CCriticalSection cs_mapRequestCount;43-extern std::map<std::string, std::string> mapAddressBook;44-extern CCriticalSection cs_mapAddressBook;45-extern std::vector<unsigned char> vchDefaultKey;46 extern double dHashesPerSec;47 extern int64 nHPSTimerStart;48+extern int64 nTimeBestReceived;49+extern CCriticalSection cs_setpwalletRegistered;50+extern std::set<CWallet*> setpwalletRegistered;51 52 // Settings53 extern int fGenerateBitcoins;54@@ -78,36 +79,26 @@55 56 57 58-59+class CReserveKey;60+class CTxDB;61+class CTxIndex;62+63+void RegisterWallet(CWallet* pwalletIn);64+void UnregisterWallet(CWallet* pwalletIn);65 bool CheckDiskSpace(uint64 nAdditionalBytes=0);66 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");67 FILE* AppendBlockFile(unsigned int& nFileRet);68-bool AddKey(const CKey& key);69-std::vector<unsigned char> GenerateNewKey();70-bool AddToWallet(const CWalletTx& wtxIn);71-void WalletUpdateSpent(const COutPoint& prevout);72-int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);73-void ReacceptWalletTransactions();74 bool LoadBlockIndex(bool fAllowNew=true);75 void PrintBlockTree();76 bool ProcessMessages(CNode* pfrom);77-bool ProcessMessage(CNode* pfrom, std::string strCommand, CDataStream& vRecv);78 bool SendMessages(CNode* pto, bool fSendTrickle);79-int64 GetBalance();80-bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);81-bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);82-bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);83-bool BroadcastTransaction(CWalletTx& wtxNew);84-std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);85-std::string SendMoneyToBitcoinAddress(std::string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);86-void GenerateBitcoins(bool fGenerate);87-void ThreadBitcoinMiner(void* parg);88+void GenerateBitcoins(bool fGenerate, CWallet* pwallet);89 CBlock* CreateNewBlock(CReserveKey& reservekey);90 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime);91 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);92-bool CheckWork(CBlock* pblock, CReserveKey& reservekey);93-void BitcoinMiner();94+bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);95 bool CheckProofOfWork(uint256 hash, unsigned int nBits);96+int GetTotalBlocksEstimate();97 bool IsInitialBlockDownload();98 std::string GetWarnings(std::string strFor);99 100@@ -120,6 +111,23 @@101 102 103 104+105+106+bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);107+108+template<typename T>109+bool WriteSetting(const std::string& strKey, const T& value)110+{111+ bool fOk = false;112+ BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)113+ {114+ std::string strWalletFile;115+ if (!GetWalletFile(pwallet, strWalletFile))116+ continue;117+ fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);118+ }119+ return fOk;120+}121 122 123 class CDiskTxPos124@@ -304,9 +312,6 @@125 {126 printf("%s\n", ToString().c_str());127 }128-129- bool IsMine() const;130- int64 GetDebit() const;131 };132 133 134@@ -353,36 +358,6 @@135 uint256 GetHash() const136 {137 return SerializeHash(*this);138- }139-140- bool IsMine() const141- {142- return ::IsMine(scriptPubKey);143- }144-145- int64 GetCredit() const146- {147- if (!MoneyRange(nValue))148- throw std::runtime_error("CTxOut::GetCredit() : value out of range");149- return (IsMine() ? nValue : 0);150- }151-152- bool IsChange() const153- {154- // On a debit transaction, a txout that's mine but isn't in the address book is change155- std::vector<unsigned char> vchPubKey;156- if (ExtractPubKey(scriptPubKey, true, vchPubKey))157- CRITICAL_BLOCK(cs_mapAddressBook)158- if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))159- return true;160- return false;161- }162-163- int64 GetChange() const164- {165- if (!MoneyRange(nValue))166- throw std::runtime_error("CTxOut::GetChange() : value out of range");167- return (IsChange() ? nValue : 0);168 }169 170 friend bool operator==(const CTxOut& a, const CTxOut& b)171@@ -529,57 +504,6 @@172 return true;173 }174 175- bool IsMine() const176- {177- BOOST_FOREACH(const CTxOut& txout, vout)178- if (txout.IsMine())179- return true;180- return false;181- }182-183- bool IsFromMe() const184- {185- return (GetDebit() > 0);186- }187-188- int64 GetDebit() const189- {190- int64 nDebit = 0;191- BOOST_FOREACH(const CTxIn& txin, vin)192- {193- nDebit += txin.GetDebit();194- if (!MoneyRange(nDebit))195- throw std::runtime_error("CTransaction::GetDebit() : value out of range");196- }197- return nDebit;198- }199-200- int64 GetCredit() const201- {202- int64 nCredit = 0;203- BOOST_FOREACH(const CTxOut& txout, vout)204- {205- nCredit += txout.GetCredit();206- if (!MoneyRange(nCredit))207- throw std::runtime_error("CTransaction::GetCredit() : value out of range");208- }209- return nCredit;210- }211-212- int64 GetChange() const213- {214- if (IsCoinBase())215- return 0;216- int64 nChange = 0;217- BOOST_FOREACH(const CTxOut& txout, vout)218- {219- nChange += txout.GetChange();220- if (!MoneyRange(nChange))221- throw std::runtime_error("CTransaction::GetChange() : value out of range");222- }223- return nChange;224- }225-226 int64 GetValueOut() const227 {228 int64 nValueOut = 0;229@@ -711,11 +635,7 @@230 bool ClientConnectInputs();231 bool CheckTransaction() const;232 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);233- bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)234- {235- CTxDB txdb("r");236- return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);237- }238+ bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);239 protected:240 bool AddToMemoryPoolUnchecked();241 public:242@@ -774,307 +694,7 @@243 bool IsInMainChain() const { return GetDepthInMainChain() > 0; }244 int GetBlocksToMaturity() const;245 bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);246- bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }247-};248-249-250-251-252-//253-// A transaction with a bunch of additional info that only the owner cares254-// about. It includes any unrecorded transactions needed to link it back255-// to the block chain.256-//257-class CWalletTx : public CMerkleTx258-{259-public:260- std::vector<CMerkleTx> vtxPrev;261- std::map<std::string, std::string> mapValue;262- std::vector<std::pair<std::string, std::string> > vOrderForm;263- unsigned int fTimeReceivedIsTxTime;264- unsigned int nTimeReceived; // time received by this node265- char fFromMe;266- std::string strFromAccount;267- std::vector<char> vfSpent;268-269- // memory only270- mutable char fDebitCached;271- mutable char fCreditCached;272- mutable char fAvailableCreditCached;273- mutable char fChangeCached;274- mutable int64 nDebitCached;275- mutable int64 nCreditCached;276- mutable int64 nAvailableCreditCached;277- mutable int64 nChangeCached;278-279- // memory only UI hints280- mutable unsigned int nTimeDisplayed;281- mutable int nLinesDisplayed;282- mutable char fConfirmedDisplayed;283-284-285- CWalletTx()286- {287- Init();288- }289-290- CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)291- {292- Init();293- }294-295- CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)296- {297- Init();298- }299-300- void Init()301- {302- vtxPrev.clear();303- mapValue.clear();304- vOrderForm.clear();305- fTimeReceivedIsTxTime = false;306- nTimeReceived = 0;307- fFromMe = false;308- strFromAccount.clear();309- vfSpent.clear();310- fDebitCached = false;311- fCreditCached = false;312- fAvailableCreditCached = false;313- fChangeCached = false;314- nDebitCached = 0;315- nCreditCached = 0;316- nAvailableCreditCached = 0;317- nChangeCached = 0;318- nTimeDisplayed = 0;319- nLinesDisplayed = 0;320- fConfirmedDisplayed = false;321- }322-323- IMPLEMENT_SERIALIZE324- (325- CWalletTx* pthis = const_cast<CWalletTx*>(this);326- if (fRead)327- pthis->Init();328- char fSpent = false;329-330- if (!fRead)331- {332- pthis->mapValue["fromaccount"] = pthis->strFromAccount;333-334- std::string str;335- BOOST_FOREACH(char f, vfSpent)336- {337- str += (f ? '1' : '0');338- if (f)339- fSpent = true;340- }341- pthis->mapValue["spent"] = str;342- }343-344- nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);345- READWRITE(vtxPrev);346- READWRITE(mapValue);347- READWRITE(vOrderForm);348- READWRITE(fTimeReceivedIsTxTime);349- READWRITE(nTimeReceived);350- READWRITE(fFromMe);351- READWRITE(fSpent);352-353- if (fRead)354- {355- pthis->strFromAccount = pthis->mapValue["fromaccount"];356-357- if (mapValue.count("spent"))358- BOOST_FOREACH(char c, pthis->mapValue["spent"])359- pthis->vfSpent.push_back(c != '0');360- else361- pthis->vfSpent.assign(vout.size(), fSpent);362- }363-364- pthis->mapValue.erase("fromaccount");365- pthis->mapValue.erase("version");366- pthis->mapValue.erase("spent");367- )368-369- // marks certain txout's as spent370- // returns true if any update took place371- bool UpdateSpent(const std::vector<char>& vfNewSpent)372- {373- bool fReturn = false;374- for (int i=0; i < vfNewSpent.size(); i++)375- {376- if (i == vfSpent.size())377- break;378-379- if (vfNewSpent[i] && !vfSpent[i])380- {381- vfSpent[i] = true;382- fReturn = true;383- fAvailableCreditCached = false;384- }385- }386- return fReturn;387- }388-389- void MarkDirty()390- {391- fCreditCached = false;392- fAvailableCreditCached = false;393- fDebitCached = false;394- fChangeCached = false;395- }396-397- void MarkSpent(unsigned int nOut)398- {399- if (nOut >= vout.size())400- throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");401- vfSpent.resize(vout.size());402- if (!vfSpent[nOut])403- {404- vfSpent[nOut] = true;405- fAvailableCreditCached = false;406- }407- }408-409- bool IsSpent(unsigned int nOut) const410- {411- if (nOut >= vout.size())412- throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");413- if (nOut >= vfSpent.size())414- return false;415- return (!!vfSpent[nOut]);416- }417-418- int64 GetDebit() const419- {420- if (vin.empty())421- return 0;422- if (fDebitCached)423- return nDebitCached;424- nDebitCached = CTransaction::GetDebit();425- fDebitCached = true;426- return nDebitCached;427- }428-429- int64 GetCredit(bool fUseCache=true) const430- {431- // Must wait until coinbase is safely deep enough in the chain before valuing it432- if (IsCoinBase() && GetBlocksToMaturity() > 0)433- return 0;434-435- // GetBalance can assume transactions in mapWallet won't change436- if (fUseCache && fCreditCached)437- return nCreditCached;438- nCreditCached = CTransaction::GetCredit();439- fCreditCached = true;440- return nCreditCached;441- }442-443- int64 GetAvailableCredit(bool fUseCache=true) const444- {445- // Must wait until coinbase is safely deep enough in the chain before valuing it446- if (IsCoinBase() && GetBlocksToMaturity() > 0)447- return 0;448-449- if (fUseCache && fAvailableCreditCached)450- return nAvailableCreditCached;451-452- int64 nCredit = 0;453- for (int i = 0; i < vout.size(); i++)454- {455- if (!IsSpent(i))456- {457- const CTxOut &txout = vout[i];458- nCredit += txout.GetCredit();459- if (!MoneyRange(nCredit))460- throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");461- }462- }463-464- nAvailableCreditCached = nCredit;465- fAvailableCreditCached = true;466- return nCredit;467- }468-469-470- int64 GetChange() const471- {472- if (fChangeCached)473- return nChangeCached;474- nChangeCached = CTransaction::GetChange();475- fChangeCached = true;476- return nChangeCached;477- }478-479- void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,480- std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;481-482- void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,483- int64& nSent, int64& nFee) const;484-485- bool IsFromMe() const486- {487- return (GetDebit() > 0);488- }489-490- bool IsConfirmed() const491- {492- // Quick answer in most cases493- if (!IsFinal())494- return false;495- if (GetDepthInMainChain() >= 1)496- return true;497- if (!IsFromMe()) // using wtx's cached debit498- return false;499-500- // If no confirmations but it's from us, we can still501- // consider it confirmed if all dependencies are confirmed502- std::map<uint256, const CMerkleTx*> mapPrev;503- std::vector<const CMerkleTx*> vWorkQueue;504- vWorkQueue.reserve(vtxPrev.size()+1);505- vWorkQueue.push_back(this);506- for (int i = 0; i < vWorkQueue.size(); i++)507- {508- const CMerkleTx* ptx = vWorkQueue[i];509-510- if (!ptx->IsFinal())511- return false;512- if (ptx->GetDepthInMainChain() >= 1)513- continue;514- if (!ptx->IsFromMe())515- return false;516-517- if (mapPrev.empty())518- BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)519- mapPrev[tx.GetHash()] = &tx;520-521- BOOST_FOREACH(const CTxIn& txin, ptx->vin)522- {523- if (!mapPrev.count(txin.prevout.hash))524- return false;525- vWorkQueue.push_back(mapPrev[txin.prevout.hash]);526- }527- }528- return true;529- }530-531- bool WriteToDisk()532- {533- return CWalletDB().WriteTx(GetHash(), *this);534- }535-536-537- int64 GetTxTime() const;538- int GetRequestCount() const;539-540- void AddSupportingTransactions(CTxDB& txdb);541-542- bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);543- bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }544-545- void RelayWalletTransaction(CTxDB& txdb);546- void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }547+ bool AcceptToMemoryPool();548 };549 550 551@@ -1727,114 +1347,6 @@552 return 0;553 return pindex->nHeight;554 }555-};556-557-558-559-560-561-562-//563-// Private key that includes an expiration date in case it never gets used.564-//565-class CWalletKey566-{567-public:568- CPrivKey vchPrivKey;569- int64 nTimeCreated;570- int64 nTimeExpires;571- std::string strComment;572- //// todo: add something to note what created it (user, getnewaddress, change)573- //// maybe should have a map<string, string> property map574-575- CWalletKey(int64 nExpires=0)576- {577- nTimeCreated = (nExpires ? GetTime() : 0);578- nTimeExpires = nExpires;579- }580-581- IMPLEMENT_SERIALIZE582- (583- if (!(nType & SER_GETHASH))584- READWRITE(nVersion);585- READWRITE(vchPrivKey);586- READWRITE(nTimeCreated);587- READWRITE(nTimeExpires);588- READWRITE(strComment);589- )590-};591-592-593-594-595-596-597-//598-// Account information.599-// Stored in wallet with key "acc"+string account name600-//601-class CAccount602-{603-public:604- std::vector<unsigned char> vchPubKey;605-606- CAccount()607- {608- SetNull();609- }610-611- void SetNull()612- {613- vchPubKey.clear();614- }615-616- IMPLEMENT_SERIALIZE617- (618- if (!(nType & SER_GETHASH))619- READWRITE(nVersion);620- READWRITE(vchPubKey);621- )622-};623-624-625-626-//627-// Internal transfers.628-// Database key is acentry<account><counter>629-//630-class CAccountingEntry631-{632-public:633- std::string strAccount;634- int64 nCreditDebit;635- int64 nTime;636- std::string strOtherAccount;637- std::string strComment;638-639- CAccountingEntry()640- {641- SetNull();642- }643-644- void SetNull()645- {646- nCreditDebit = 0;647- nTime = 0;648- strAccount.clear();649- strOtherAccount.clear();650- strComment.clear();651- }652-653- IMPLEMENT_SERIALIZE654- (655- if (!(nType & SER_GETHASH))656- READWRITE(nVersion);657- // Note: strAccount is serialized as part of the key, not here.658- READWRITE(nCreditDebit);659- READWRITE(nTime);660- READWRITE(strOtherAccount);661- READWRITE(strComment);662- )663 };664 665 666@@ -2053,14 +1565,10 @@667 668 669 670+671 extern std::map<uint256, CTransaction> mapTransactions;672-extern std::map<uint256, CWalletTx> mapWallet;673-extern std::vector<uint256> vWalletUpdated;674-extern CCriticalSection cs_mapWallet;675-extern std::map<std::vector<unsigned char>, CPrivKey> mapKeys;676 extern std::map<uint160, std::vector<unsigned char> > mapPubKeys;677-extern CCriticalSection cs_mapKeys;678-extern CKey keyUser;679+extern CCriticalSection cs_mapPubKeys;680 681 #endif682
makefile.linux-mingw (added)
1--- /dev/null2+++ v0.3.24/makefile.linux-mingw3@@ -1 +1,112 @@4+# Copyright (c) 2009-2010 Satoshi Nakamoto5+# Distributed under the MIT/X11 software license, see the accompanying6+# file license.txt or http://www.opensource.org/licenses/mit-license.php.7 8+DEPSDIR:=/usr/i586-mingw32msvc9+10+INCLUDEPATHS= \11+ -I"$(DEPSDIR)/boost_1_43_0" \12+ -I"$(DEPSDIR)/db-4.7.25.NC/build_unix" \13+ -I"$(DEPSDIR)/openssl-1.0.0d/include" \14+ -I"$(DEPSDIR)/wxWidgets-2.9.1/lib/gcc_lib/mswud" \15+ -I"$(DEPSDIR)/wxWidgets-2.9.1/include" \16+ -I"$(DEPSDIR)/wxWidgets-2.9.1/lib/wx/include/i586-mingw32msvc-msw-unicode-static-2.9/" \17+ -I"$(DEPSDIR)"18+19+LIBPATHS= \20+ -L"$(DEPSDIR)/boost_1_43_0/stage/lib" \21+ -L"$(DEPSDIR)/db-4.7.25.NC/build_unix" \22+ -L"$(DEPSDIR)/openssl-1.0.0d" \23+ -L"$(DEPSDIR)/wxWidgets-2.9.1/lib"24+25+WXLIBS= -l wx_mswu-2.9-i586-mingw32msvc26+27+LIBS= \28+ -l boost_system-mt-s \29+ -l boost_filesystem-mt-s \30+ -l boost_program_options-mt-s \31+ -l boost_thread_win32-mt-s \32+ -l db_cxx \33+ -l ssl \34+ -l crypto35+36+DEFS=-D_MT -DWIN32 -D__WXMSW__ -D_WINDOWS -DNOPCH -DUSE_SSL37+DEBUGFLAGS=-g -D__WXDEBUG__38+CFLAGS=-O2 -w -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(DEFS) $(INCLUDEPATHS)39+HEADERS=headers.h strlcpy.h serialize.h uint256.h util.h key.h bignum.h base58.h \40+ script.h db.h net.h irc.h keystore.h main.h wallet.h rpc.h uibase.h ui.h noui.h init.h41+42+bitcoin.exe: USE_UPNP:=143+ ifdef USE_UPNP44+ INCLUDEPATHS += -I"$(DEPSDIR)/upnpc-exe-win32-20110215"45+ LIBPATHS += -L"$(DEPSDIR)/upnpc-exe-win32-20110215"46+ LIBS += -l miniupnpc -l iphlpapi47+ DEFS += -DSTATICLIB -DUSE_UPNP=$(USE_UPNP)48+ endif49+50+bitcoind.exe: USE_UPNP:=051+ ifdef USE_UPNP52+ INCLUDEPATHS += -I"$(DEPSDIR)/upnpc-exe-win32-20110215"53+ LIBPATHS += -L"$(DEPSDIR)/upnpc-exe-win32-20110215"54+ LIBS += -l miniupnpc -l iphlpapi55+ DEFS += -DSTATICLIB -DUSE_UPNP=$(USE_UPNP)56+ endif57+58+LIBS += -l mingwthrd -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 shlwapi59+60+OBJS= \61+ obj/util.o \62+ obj/script.o \63+ obj/db.o \64+ obj/net.o \65+ obj/irc.o \66+ obj/keystore.o \67+ obj/main.o \68+ obj/wallet.o \69+ obj/rpc.o \70+ obj/init.o \71+ cryptopp/obj/sha.o \72+ cryptopp/obj/cpu.o73+74+75+all: bitcoin.exe76+77+78+obj/%.o: %.cpp $(HEADERS)79+ i586-mingw32msvc-g++ -c $(CFLAGS) -DGUI -o $@ $<80+81+cryptopp/obj/%.o: cryptopp/%.cpp82+ i586-mingw32msvc-g++ -c $(CFLAGS) -O3 -DCRYPTOPP_DISABLE_ASM -o $@ $<83+84+obj/ui_res.o: ../share/ui.rc ../share/pixmaps/bitcoin.ico ../share/pixmaps/check.ico ../share/pixmaps/send16.bmp ../share/pixmaps/send16mask.bmp ../share/pixmaps/send16masknoshadow.bmp ../share/pixmaps/send20.bmp ../share/pixmaps/send20mask.bmp ../share/pixmaps/addressbook16.bmp ../share/pixmaps/addressbook16mask.bmp ../share/pixmaps/addressbook20.bmp ../share/pixmaps/addressbook20mask.bmp85+ i586-mingw32msvc-windres $(DEFS) $(INCLUDEPATHS) -o $@ -i $<86+87+bitcoin.exe: $(OBJS) obj/ui.o obj/uibase.o obj/ui_res.o88+ i586-mingw32msvc-g++ $(CFLAGS) -mwindows -Wl,--subsystem,windows -o $@ $(LIBPATHS) $^ $(WXLIBS) $(LIBS)89+90+91+obj/nogui/%.o: %.cpp $(HEADERS)92+ i586-mingw32msvc-g++ -c $(CFLAGS) -o $@ $<93+94+bitcoind.exe: $(OBJS:obj/%=obj/nogui/%) obj/ui_res.o95+ i586-mingw32msvc-g++ $(CFLAGS) -o $@ $(LIBPATHS) $^ $(LIBS)96+97+98+obj/test/%.o: obj/test/%.cpp $(HEADERS)99+ i586-mingw32msvc-g++ -c $(CFLAGS) -o $@ $<100+101+test_bitcoin.exe: obj/test/test_bitcoin.o102+ i586-mingw32msvc-g++ $(CFLAGS) -o $@ $(LIBPATHS) $^ $(LIBS) -lboost_unit_test_framework-mt-s103+104+105+clean:106+ -rm -f obj/*.o107+ -rm -f obj/nogui/*.o108+ -rm -f obj/test/*.o109+ -rm -f cryptopp/obj/*.o110+ -rm -f test/*.o111+ -rm -f headers.h.gch112+ -rm -f bitcoin.exe113+ -rm -f bitcoind.exe114+ -rm -f test_bitcoin.exe115+
makefile.mingw (modified)
1--- v0.3.23/makefile.mingw2+++ v0.3.24/makefile.mingw3@@ -33,7 +33,7 @@4 DEBUGFLAGS=-g -D__WXDEBUG__5 CFLAGS=-mthreads -O2 -w -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(DEFS) $(INCLUDEPATHS)6 HEADERS=headers.h strlcpy.h serialize.h uint256.h util.h key.h bignum.h base58.h \7- script.h db.h net.h irc.h main.h rpc.h uibase.h ui.h noui.h init.h8+ script.h db.h net.h irc.h keystore.h main.h wallet.h rpc.h uibase.h ui.h noui.h init.h9 10 ifdef USE_UPNP11 INCLUDEPATHS += -I"C:\upnpc-exe-win32-20110215"12@@ -50,7 +50,9 @@13 obj/db.o \14 obj/net.o \15 obj/irc.o \16+ obj/keystore.o \17 obj/main.o \18+ obj/wallet.o \19 obj/rpc.o \20 obj/init.o \21 cryptopp/obj/sha.o \22@@ -79,10 +81,18 @@23 bitcoind.exe: $(OBJS:obj/%=obj/nogui/%) obj/ui_res.o24 g++ $(CFLAGS) -o $@ $(LIBPATHS) $^ $(LIBS)25 26+obj/test/%.o: obj/test/%.cpp $(HEADERS)27+ g++ -c $(CFLAGS) -o $@ $<28+29+test_bitcoin: obj/test/test_bitcoin.o30+ g++ $(CFLAGS) -o $@ $(LIBPATHS) $^ $(LIBS)31 32 clean:33+ -del /Q bitcoin bitcoind test_bitcoin34 -del /Q obj\*35 -del /Q obj\nogui\*36+ -del /Q obj\test\*37 -del /Q cryptopp\obj\*38+ -del /Q test\*.o39 -del /Q headers.h.gch40
makefile.osx (modified)
1--- v0.3.23/makefile.osx2+++ v0.3.24/makefile.osx3@@ -33,7 +33,7 @@4 # ppc doesn't work because we don't support big-endian5 CFLAGS=-mmacosx-version-min=10.5 -arch i386 -arch x86_64 -O3 -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(DEFS) $(INCLUDEPATHS)6 HEADERS=headers.h strlcpy.h serialize.h uint256.h util.h key.h bignum.h base58.h \7- script.h db.h net.h irc.h main.h rpc.h uibase.h ui.h noui.h init.h8+ script.h db.h net.h irc.h keystore.h main.h wallet.h rpc.h uibase.h ui.h noui.h init.h9 10 OBJS= \11 obj/util.o \12@@ -41,7 +41,9 @@13 obj/db.o \14 obj/net.o \15 obj/irc.o \16+ obj/keystore.o \17 obj/main.o \18+ obj/wallet.o \19 obj/rpc.o \20 obj/init.o \21 cryptopp/obj/sha.o \22@@ -72,10 +74,16 @@23 bitcoind: $(OBJS:obj/%=obj/nogui/%)24 $(CXX) $(CFLAGS) -o $@ $(LIBPATHS) $^ $(LIBS)25 26+obj/test/%.o: test/%.cpp $(HEADERS)27+ $(CXX) -c $(CFLAGS) -o $@ $<28+29+test_bitcoin: obj/test/test_bitcoin.o30+ $(CXX) $(CFLAGS) -o $@ $(LIBPATHS) $^ $(LIBS) -lboost_unit_test_framework31 32 clean:33- -rm -f bitcoin bitcoind34+ -rm -f bitcoin bitcoind test_bitcoin35 -rm -f obj/*.o36 -rm -f obj/nogui/*.o37+ -rm -f obj/test/*.o38 -rm -f cryptopp/obj/*.o39
makefile.unix (modified)
1--- v0.3.23/makefile.unix2+++ v0.3.24/makefile.unix3@@ -39,7 +39,7 @@4 DEBUGFLAGS=-g -D__WXDEBUG__5 CXXFLAGS=-O2 -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(DEFS)6 HEADERS=headers.h strlcpy.h serialize.h uint256.h util.h key.h bignum.h base58.h \7- script.h db.h net.h irc.h main.h rpc.h uibase.h ui.h noui.h init.h8+ script.h db.h net.h irc.h keystore.h main.h wallet.h rpc.h uibase.h ui.h noui.h init.h9 10 OBJS= \11 obj/util.o \12@@ -47,7 +47,9 @@13 obj/db.o \14 obj/net.o \15 obj/irc.o \16+ obj/keystore.o \17 obj/main.o \18+ obj/wallet.o \19 obj/rpc.o \20 obj/init.o \21 cryptopp/obj/sha.o \22@@ -73,12 +75,17 @@23 bitcoind: $(OBJS:obj/%=obj/nogui/%)24 $(CXX) $(CXXFLAGS) -o $@ $^ $(LIBS)25 26+obj/test/%.o: test/%.cpp $(HEADERS)27+ $(CXX) -c $(CFLAGS) -o $@ $<28+29+test_bitcoin: obj/test/test_bitcoin.o30+ $(CXX) $(CFLAGS) -o $@ $(LIBPATHS) $^ $(LIBS) -lboost_unit_test_framework31 32 clean:33+ -rm -f bitcoin bitcoind test_bitcoin34 -rm -f obj/*.o35 -rm -f obj/nogui/*.o36+ -rm -f obj/test/*.o37 -rm -f cryptopp/obj/*.o38 -rm -f headers.h.gch39- -rm -f bitcoin40- -rm -f bitcoind41
makefile.vc (modified)
1--- v0.3.23/makefile.vc2+++ v0.3.24/makefile.vc3@@ -8,18 +8,24 @@4 /I"/db/build_windows" \5 /I"/openssl/include" \6 /I"/wxwidgets/lib/vc_lib/mswu" \7- /I"/wxwidgets/include"8+ /I"/wxwidgets/include" /9+ /I"/miniupnpc"10 11 LIBPATHS= \12 /LIBPATH:"/boost/stage/lib" \13 /LIBPATH:"/db/build_windows/Release" \14 /LIBPATH:"/openssl/lib" \15 /LIBPATH:"/wxwidgets/lib/vc_lib" \16+ /LIBPATH:"/miniupnpc/msvc/Release" \17 /NODEFAULTLIB:libc.lib /NODEFAULTLIB:libcmt.lib \18 /NODEFAULTLIB:libcd.lib /NODEFAULTLIB:libcmtd.lib \19 /NODEFAULTLIB:msvcrtd.lib20 21 WXLIBS=wxmsw29u.lib wxtiff.lib wxjpeg.lib wxpng.lib wxzlib.lib22+23+USE_UPNP=024+25+DEFS=/DWIN32 /D__WXMSW__ /D_WINDOWS /DNOPCH /DNOMINMAX26 27 LIBS= \28 libboost_system-vc100-mt.lib \29@@ -27,14 +33,20 @@30 libboost_program_options-vc100-mt.lib \31 libboost_thread-vc100-mt.lib \32 libdb47s.lib \33- libeay32.lib \34+ libeay32.lib35+36+!IFDEF USE_UPNP37+LIBS=$(LIBS) miniupnpc.lib38+DEFS=$(DEFS) /DUSE_UPNP=$(USE_UPNP)39+!ENDIF40+41+LIBS=$(LIBS) \42 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.lib43 44-DEFS=/DWIN32 /D__WXMSW__ /D_WINDOWS /DNOPCH45 DEBUGFLAGS=/Os46 CFLAGS=/MD /c /nologo /EHsc /GR /Zm300 $(DEBUGFLAGS) $(DEFS) $(INCLUDEPATHS)47 HEADERS=headers.h strlcpy.h serialize.h uint256.h util.h key.h bignum.h base58.h \48- script.h db.h net.h irc.h main.h rpc.h uibase.h ui.h noui.h init.h49+ script.h db.h net.h irc.h main.h rpc.h uibase.h ui.h noui.h init.h wallet.h keystore.h50 51 OBJS= \52 obj\util.obj \53@@ -42,11 +54,17 @@54 obj\db.obj \55 obj\net.obj \56 obj\irc.obj \57+ obj\keystore.obj \58 obj\main.obj \59+ obj\wallet.obj \60 obj\rpc.obj \61- obj\init.obj \62+ obj\init.obj63+64+CRYPTOPP_OBJS= \65 cryptopp\obj\sha.obj \66 cryptopp\obj\cpu.obj67+68+RC=../share69 70 71 all: bitcoin.exe72@@ -65,7 +83,11 @@73 74 obj\irc.obj: $(HEADERS)75 76+obj\keystore.obj: $(HEADERS)77+78 obj\main.obj: $(HEADERS)79+80+obj\wallet.obj: $(HEADERS)81 82 obj\rpc.obj: $(HEADERS)83 84@@ -81,13 +103,13 @@85 cryptopp\obj\cpu.obj: cryptopp\cpu.cpp86 cl $(CFLAGS) /O2 /DCRYPTOPP_DISABLE_ASM /Fo$@ %s87 88-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.bmp89+obj\ui.res: $(RC)/ui.rc $(RC)/pixmaps/bitcoin.ico $(RC)/pixmaps/check.ico $(RC)/pixmaps/send16.bmp $(RC)/pixmaps/send16mask.bmp $(RC)/pixmaps/send16masknoshadow.bmp $(RC)/pixmaps/send20.bmp $(RC)/pixmaps/send20mask.bmp $(RC)/pixmaps/addressbook16.bmp $(RC)/pixmaps/addressbook16mask.bmp $(RC)/pixmaps/addressbook20.bmp $(RC)/pixmaps/addressbook20mask.bmp90 rc $(INCLUDEPATHS) $(DEFS) /Fo$@ %s91 92-bitcoin.exe: $(OBJS) obj\ui.obj obj\uibase.obj obj\ui.res93+bitcoin.exe: $(OBJS) $(CRYPTOPP_OBJS) obj\ui.obj obj\uibase.obj obj\ui.res94 link /nologo /SUBSYSTEM:WINDOWS /OUT:$@ $(LIBPATHS) $** $(WXLIBS) $(LIBS)95 96-97+ 98 .cpp{obj\nogui}.obj:99 cl $(CFLAGS) /Fo$@ %s100 101@@ -101,13 +123,17 @@102 103 obj\nogui\irc.obj: $(HEADERS)104 105+obj\nogui\keystore.obj: $(HEADERS)106+107 obj\nogui\main.obj: $(HEADERS)108+109+obj\nogui\wallet.obj: $(HEADERS)110 111 obj\nogui\rpc.obj: $(HEADERS)112 113 obj\nogui\init.obj: $(HEADERS)114 115-bitcoind.exe: $(OBJS:obj\=obj\nogui\) obj\ui.res116+bitcoind.exe: $(OBJS:obj\=obj\nogui\) $(CRYPTOPP_OBJS) obj\ui.res117 link /nologo /OUT:$@ $(LIBPATHS) $** $(LIBS)118 119
net.cpp (modified)
1--- v0.3.23/net.cpp2+++ v0.3.24/net.cpp3@@ -3,6 +3,20 @@4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.5 6 #include "headers.h"7+#include "irc.h"8+#include "db.h"9+#include "net.h"10+#include "init.h"11+#include "strlcpy.h"12+13+#ifdef __WXMSW__14+#include <string.h>15+// This file can be downloaded as a part of the Windows Platform SDK16+// and is required for Bitcoin binaries to work properly on versions17+// of Windows before XP. If you are doing builds of Bitcoin for18+// public release, you should uncomment this line.19+//#include <WSPiApi.h>20+#endif21 22 #ifdef USE_UPNP23 #include <miniupnpc/miniwget.h>24@@ -143,7 +157,7 @@25 }26 if (nRet != 0)27 {28- printf("connect() failed after select(): %i\n",nRet);29+ printf("connect() failed after select(): %s\n",strerror(nRet));30 closesocket(hSocket);31 return false;32 }33@@ -154,7 +168,7 @@34 else35 #endif36 {37- printf("connect() failed: %s\n",WSAGetLastError());38+ printf("connect() failed: %i\n",WSAGetLastError());39 closesocket(hSocket);40 return false;41 }42@@ -910,7 +924,7 @@43 CDataStream& vRecv = pnode->vRecv;44 unsigned int nPos = vRecv.size();45 46- if (nPos > 1000*GetArg("-maxreceivebuffer", 10*1000)) {47+ if (nPos > ReceiveBufferSize()) {48 if (!pnode->fDisconnect)49 printf("socket recv flood control disconnect (%d bytes)\n", vRecv.size());50 pnode->CloseSocketDisconnect();51@@ -975,7 +989,7 @@52 pnode->CloseSocketDisconnect();53 }54 }55- if (vSend.size() > 1000*GetArg("-maxsendbuffer", 10*1000)) {56+ if (vSend.size() > SendBufferSize()) {57 if (!pnode->fDisconnect)58 printf("socket send flood control disconnect (%d bytes)\n", vSend.size());59 pnode->CloseSocketDisconnect();60@@ -1112,7 +1126,7 @@61 if (fUseUPnP != fMapPort)62 {63 fUseUPnP = fMapPort;64- CWalletDB().WriteSetting("fUseUPnP", fUseUPnP);65+ WriteSetting("fUseUPnP", fUseUPnP);66 }67 if (fUseUPnP && vnThreadsRunning[5] < 1)68 {69@@ -1134,25 +1148,29 @@70 static const char *strDNSSeed[] = {71 "bitseed.xf2.org",72 "bitseed.bitcoin.org.uk",73+ "dnsseed.bluematt.me",74 };75 76 void DNSAddressSeed()77 {78 int found = 0;79 80- printf("Loading addresses from DNS seeds (could take a while)\n");81-82- for (int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {83- vector<CAddress> vaddr;84- if (Lookup(strDNSSeed[seed_idx], vaddr, NODE_NETWORK, -1, true))85- {86- BOOST_FOREACH (CAddress& addr, vaddr)87- {88- if (addr.GetByte(3) != 127)89+ if (!fTestNet)90+ {91+ printf("Loading addresses from DNS seeds (could take a while)\n");92+93+ for (int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {94+ vector<CAddress> vaddr;95+ if (Lookup(strDNSSeed[seed_idx], vaddr, NODE_NETWORK, -1, true))96+ {97+ BOOST_FOREACH (CAddress& addr, vaddr)98 {99- addr.nTime = 0;100- AddAddress(addr);101- found++;102+ if (addr.GetByte(3) != 127)103+ {104+ addr.nTime = 0;105+ AddAddress(addr);106+ found++;107+ }108 }109 }110 }111@@ -1693,7 +1711,7 @@112 printf("Error: CreateThread(ThreadMessageHandler) failed\n");113 114 // Generate coins in the background115- GenerateBitcoins(fGenerateBitcoins);116+ GenerateBitcoins(fGenerateBitcoins, pwalletMain);117 }118 119 bool StopNode()
net.h (modified)
1--- v0.3.23/net.h2+++ v0.3.24/net.h3@@ -23,6 +23,8 @@4 5 6 7+inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 10*1000); }8+inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 10*1000); }9 inline unsigned short GetDefaultPort() { return fTestNet ? 18333 : 8333; }10 static const unsigned int PUBLISH_HOPS = 5;11 enum
noui.h (modified)
1--- v0.3.23/noui.h2+++ v0.3.24/noui.h3@@ -5,6 +5,8 @@4 #define BITCOIN_NOUI_H5 6 #include <string>7+#include <boost/function.hpp>8+#include "wallet.h"9 10 typedef void wxWindow;11 #define wxYES 0x00000002
rpc.cpp (modified)
1--- v0.3.23/rpc.cpp2+++ v0.3.24/rpc.cpp3@@ -4,12 +4,18 @@4 5 #include "headers.h"6 #include "cryptopp/sha.h"7+#include "db.h"8+#include "net.h"9+#include "init.h"10 #undef printf11 #include <boost/asio.hpp>12 #include <boost/iostreams/concepts.hpp>13 #include <boost/iostreams/stream.hpp>14+#include <boost/algorithm/string.hpp>15 #ifdef USE_SSL16 #include <boost/asio/ssl.hpp> 17+#include <boost/filesystem.hpp>18+#include <boost/filesystem/fstream.hpp>19 typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> SSLStream;20 #endif21 #include "json/json_spirit_reader_template.h"22@@ -259,14 +265,14 @@23 {24 int nGenProcLimit = params[1].get_int();25 fLimitProcessors = (nGenProcLimit != -1);26- CWalletDB().WriteSetting("fLimitProcessors", fLimitProcessors);27+ WriteSetting("fLimitProcessors", fLimitProcessors);28 if (nGenProcLimit != -1)29- CWalletDB().WriteSetting("nLimitProcessors", nLimitProcessors = nGenProcLimit);30+ WriteSetting("nLimitProcessors", nLimitProcessors = nGenProcLimit);31 if (nGenProcLimit == 0)32 fGenerate = false;33 }34 35- GenerateBitcoins(fGenerate);36+ GenerateBitcoins(fGenerate, pwalletMain);37 return Value::null;38 }39 40@@ -293,7 +299,7 @@41 42 Object obj;43 obj.push_back(Pair("version", (int)VERSION));44- obj.push_back(Pair("balance", ValueFromAmount(GetBalance())));45+ obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));46 obj.push_back(Pair("blocks", (int)nBestHeight));47 obj.push_back(Pair("connections", (int)vNodes.size()));48 obj.push_back(Pair("proxy", (fUseProxy ? addrProxy.ToStringIPPort() : string())));49@@ -302,7 +308,7 @@50 obj.push_back(Pair("difficulty", (double)GetDifficulty()));51 obj.push_back(Pair("hashespersec", gethashespersec(params, false)));52 obj.push_back(Pair("testnet", fTestNet));53- obj.push_back(Pair("keypoololdest", (boost::int64_t)GetOldestKeyPoolTime()));54+ obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));55 obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));56 obj.push_back(Pair("errors", GetWarnings("statusbar")));57 return obj;58@@ -324,19 +330,22 @@59 strAccount = AccountFromValue(params[0]);60 61 // Generate a new key that is added to wallet62- string strAddress = PubKeyToAddress(GetKeyFromKeyPool());63-64- SetAddressBookName(strAddress, strAccount);65+ string strAddress = PubKeyToAddress(pwalletMain->GetKeyFromKeyPool());66+67+ // This could be done in the same main CS as GetKeyFromKeyPool.68+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)69+ pwalletMain->SetAddressBookName(strAddress, strAccount);70+71 return strAddress;72 }73 74 75-// requires cs_main, cs_mapWallet locks76+// requires cs_main, cs_mapWallet, cs_mapAddressBook locks77 string GetAccountAddress(string strAccount, bool bForceNew=false)78 {79 string strAddress;80 81- CWalletDB walletdb;82+ CWalletDB walletdb(pwalletMain->strWalletFile);83 walletdb.TxnBegin();84 85 CAccount account;86@@ -347,8 +356,8 @@87 {88 CScript scriptPubKey;89 scriptPubKey.SetBitcoinAddress(account.vchPubKey);90- for (map<uint256, CWalletTx>::iterator it = mapWallet.begin();91- it != mapWallet.end() && !account.vchPubKey.empty();92+ for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();93+ it != pwalletMain->mapWallet.end() && !account.vchPubKey.empty();94 ++it)95 {96 const CWalletTx& wtx = (*it).second;97@@ -361,9 +370,9 @@98 // Generate a new key99 if (account.vchPubKey.empty() || bForceNew)100 {101- account.vchPubKey = GetKeyFromKeyPool();102+ account.vchPubKey = pwalletMain->GetKeyFromKeyPool();103 string strAddress = PubKeyToAddress(account.vchPubKey);104- SetAddressBookName(strAddress, strAccount);105+ pwalletMain->SetAddressBookName(strAddress, strAccount);106 walletdb.WriteAccount(strAccount, account);107 }108 109@@ -386,7 +395,8 @@110 Value ret;111 112 CRITICAL_BLOCK(cs_main)113- CRITICAL_BLOCK(cs_mapWallet)114+ CRITICAL_BLOCK(pwalletMain->cs_mapWallet)115+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)116 {117 ret = GetAccountAddress(strAccount);118 }119@@ -416,18 +426,19 @@120 121 // Detect when changing the account of an address that is the 'unused current key' of another account:122 CRITICAL_BLOCK(cs_main)123- CRITICAL_BLOCK(cs_mapWallet)124- CRITICAL_BLOCK(cs_mapAddressBook)125- {126- if (mapAddressBook.count(strAddress))127- {128- string strOldAccount = mapAddressBook[strAddress];129+ CRITICAL_BLOCK(pwalletMain->cs_mapWallet)130+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)131+ {132+ if (pwalletMain->mapAddressBook.count(strAddress))133+ {134+ string strOldAccount = pwalletMain->mapAddressBook[strAddress];135 if (strAddress == GetAccountAddress(strOldAccount))136 GetAccountAddress(strOldAccount, true);137 }138- }139-140- SetAddressBookName(strAddress, strAccount);141+142+ pwalletMain->SetAddressBookName(strAddress, strAccount);143+ }144+145 return Value::null;146 }147 148@@ -442,10 +453,10 @@149 string strAddress = params[0].get_str();150 151 string strAccount;152- CRITICAL_BLOCK(cs_mapAddressBook)153- {154- map<string, string>::iterator mi = mapAddressBook.find(strAddress);155- if (mi != mapAddressBook.end() && !(*mi).second.empty())156+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)157+ {158+ map<string, string>::iterator mi = pwalletMain->mapAddressBook.find(strAddress);159+ if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())160 strAccount = (*mi).second;161 }162 return strAccount;163@@ -463,9 +474,9 @@164 165 // Find all addresses that have the given account166 Array ret;167- CRITICAL_BLOCK(cs_mapAddressBook)168- {169- BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)170+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)171+ {172+ BOOST_FOREACH(const PAIRTYPE(string, string)& item, pwalletMain->mapAddressBook)173 {174 const string& strAddress = item.first;175 const string& strName = item.second;176@@ -518,7 +529,7 @@177 178 CRITICAL_BLOCK(cs_main)179 {180- string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);181+ string strError = pwalletMain->SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);182 if (strError != "")183 throw JSONRPCError(-4, strError);184 }185@@ -539,7 +550,7 @@186 CScript scriptPubKey;187 if (!scriptPubKey.SetBitcoinAddress(strAddress))188 throw JSONRPCError(-5, "Invalid bitcoin address");189- if (!IsMine(scriptPubKey))190+ if (!IsMine(*pwalletMain,scriptPubKey))191 return (double)0.0;192 193 // Minimum confirmations194@@ -549,9 +560,9 @@195 196 // Tally197 int64 nAmount = 0;198- CRITICAL_BLOCK(cs_mapWallet)199- {200- for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)201+ CRITICAL_BLOCK(pwalletMain->cs_mapWallet)202+ {203+ for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)204 {205 const CWalletTx& wtx = (*it).second;206 if (wtx.IsCoinBase() || !wtx.IsFinal())207@@ -570,9 +581,9 @@208 209 void GetAccountPubKeys(string strAccount, set<CScript>& setPubKey)210 {211- CRITICAL_BLOCK(cs_mapAddressBook)212- {213- BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)214+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)215+ {216+ BOOST_FOREACH(const PAIRTYPE(string, string)& item, pwalletMain->mapAddressBook)217 {218 const string& strAddress = item.first;219 const string& strName = item.second;220@@ -581,7 +592,7 @@221 // We're only counting our own valid bitcoin addresses and not ip addresses222 CScript scriptPubKey;223 if (scriptPubKey.SetBitcoinAddress(strAddress))224- if (IsMine(scriptPubKey))225+ if (IsMine(*pwalletMain,scriptPubKey))226 setPubKey.insert(scriptPubKey);227 }228 }229@@ -608,9 +619,9 @@230 231 // Tally232 int64 nAmount = 0;233- CRITICAL_BLOCK(cs_mapWallet)234- {235- for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)236+ CRITICAL_BLOCK(pwalletMain->cs_mapWallet)237+ {238+ for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)239 {240 const CWalletTx& wtx = (*it).second;241 if (wtx.IsCoinBase() || !wtx.IsFinal())242@@ -630,10 +641,10 @@243 int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)244 {245 int64 nBalance = 0;246- CRITICAL_BLOCK(cs_mapWallet)247+ CRITICAL_BLOCK(pwalletMain->cs_mapWallet)248 {249 // Tally wallet transactions250- for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)251+ for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)252 {253 const CWalletTx& wtx = (*it).second;254 if (!wtx.IsFinal())255@@ -656,7 +667,7 @@256 257 int64 GetAccountBalance(const string& strAccount, int nMinDepth)258 {259- CWalletDB walletdb;260+ CWalletDB walletdb(pwalletMain->strWalletFile);261 return GetAccountBalance(walletdb, strAccount, nMinDepth);262 }263 264@@ -670,7 +681,7 @@265 "If [account] is specified, returns the balance in the account.");266 267 if (params.size() == 0)268- return ValueFromAmount(GetBalance());269+ return ValueFromAmount(pwalletMain->GetBalance());270 271 int nMinDepth = 1;272 if (params.size() > 1)273@@ -681,7 +692,7 @@274 // (GetBalance() sums up all unspent TxOuts)275 // getbalance and getbalance '*' should always return the same number.276 int64 nBalance = 0;277- for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)278+ for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)279 {280 const CWalletTx& wtx = (*it).second;281 if (!wtx.IsFinal())282@@ -729,9 +740,9 @@283 if (params.size() > 4)284 strComment = params[4].get_str();285 286- CRITICAL_BLOCK(cs_mapWallet)287- {288- CWalletDB walletdb;289+ CRITICAL_BLOCK(pwalletMain->cs_mapWallet)290+ {291+ CWalletDB walletdb(pwalletMain->strWalletFile);292 walletdb.TxnBegin();293 294 int64 nNow = GetAdjustedTime();295@@ -782,7 +793,7 @@296 wtx.mapValue["to"] = params[5].get_str();297 298 CRITICAL_BLOCK(cs_main)299- CRITICAL_BLOCK(cs_mapWallet)300+ CRITICAL_BLOCK(pwalletMain->cs_mapWallet)301 {302 // Check funds303 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);304@@ -790,7 +801,7 @@305 throw JSONRPCError(-6, "Account has insufficient funds");306 307 // Send308- string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);309+ string strError = pwalletMain->SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);310 if (strError != "")311 throw JSONRPCError(-4, strError);312 }313@@ -839,7 +850,7 @@314 }315 316 CRITICAL_BLOCK(cs_main)317- CRITICAL_BLOCK(cs_mapWallet)318+ CRITICAL_BLOCK(pwalletMain->cs_mapWallet)319 {320 // Check funds321 int64 nBalance = GetAccountBalance(strAccount, nMinDepth);322@@ -847,16 +858,16 @@323 throw JSONRPCError(-6, "Account has insufficient funds");324 325 // Send326- CReserveKey keyChange;327+ CReserveKey keyChange(pwalletMain);328 int64 nFeeRequired = 0;329- bool fCreated = CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);330+ bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);331 if (!fCreated)332 {333- if (totalAmount + nFeeRequired > GetBalance())334+ if (totalAmount + nFeeRequired > pwalletMain->GetBalance())335 throw JSONRPCError(-6, "Insufficient funds");336 throw JSONRPCError(-4, "Transaction creation failed");337 }338- if (!CommitTransaction(wtx, keyChange))339+ if (!pwalletMain->CommitTransaction(wtx, keyChange))340 throw JSONRPCError(-4, "Transaction commit failed");341 }342 343@@ -889,9 +900,9 @@344 345 // Tally346 map<uint160, tallyitem> mapTally;347- CRITICAL_BLOCK(cs_mapWallet)348- {349- for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)350+ CRITICAL_BLOCK(pwalletMain->cs_mapWallet)351+ {352+ for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)353 {354 const CWalletTx& wtx = (*it).second;355 if (wtx.IsCoinBase() || !wtx.IsFinal())356@@ -918,9 +929,9 @@357 // Reply358 Array ret;359 map<string, tallyitem> mapAccountTally;360- CRITICAL_BLOCK(cs_mapAddressBook)361- {362- BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)363+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)364+ {365+ BOOST_FOREACH(const PAIRTYPE(string, string)& item, pwalletMain->mapAddressBook)366 {367 const string& strAddress = item.first;368 const string& strAccount = item.second;369@@ -1056,13 +1067,13 @@370 371 // Received372 if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)373- CRITICAL_BLOCK(cs_mapAddressBook)374+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)375 {376 BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)377 {378 string account;379- if (mapAddressBook.count(r.first))380- account = mapAddressBook[r.first];381+ if (pwalletMain->mapAddressBook.count(r.first))382+ account = pwalletMain->mapAddressBook[r.first];383 if (fAllAccounts || (account == strAccount))384 {385 Object entry;386@@ -1114,16 +1125,16 @@387 nFrom = params[2].get_int();388 389 Array ret;390- CWalletDB walletdb;391-392- CRITICAL_BLOCK(cs_mapWallet)393+ CWalletDB walletdb(pwalletMain->strWalletFile);394+395+ CRITICAL_BLOCK(pwalletMain->cs_mapWallet)396 {397 // Firs: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap:398 typedef pair<CWalletTx*, CAccountingEntry*> TxPair;399 typedef multimap<int64, TxPair > TxItems;400 TxItems txByTime;401 402- for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)403+ for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)404 {405 CWalletTx* wtx = &((*it).second);406 txByTime.insert(make_pair(wtx->GetTxTime(), TxPair(wtx, (CAccountingEntry*)0)));407@@ -1175,16 +1186,16 @@408 nMinDepth = params[0].get_int();409 410 map<string, int64> mapAccountBalances;411- CRITICAL_BLOCK(cs_mapWallet)412- CRITICAL_BLOCK(cs_mapAddressBook)413- {414- BOOST_FOREACH(const PAIRTYPE(string, string)& entry, mapAddressBook) {415+ CRITICAL_BLOCK(pwalletMain->cs_mapWallet)416+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)417+ {418+ BOOST_FOREACH(const PAIRTYPE(string, string)& entry, pwalletMain->mapAddressBook) {419 uint160 hash160;420 if(AddressToHash160(entry.first, hash160) && mapPubKeys.count(hash160)) // This address belongs to me421 mapAccountBalances[entry.second] = 0;422 }423 424- for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)425+ for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)426 {427 const CWalletTx& wtx = (*it).second;428 int64 nGeneratedImmature, nGeneratedMature, nFee;429@@ -1199,8 +1210,8 @@430 {431 mapAccountBalances[""] += nGeneratedMature;432 BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)433- if (mapAddressBook.count(r.first))434- mapAccountBalances[mapAddressBook[r.first]] += r.second;435+ if (pwalletMain->mapAddressBook.count(r.first))436+ mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;437 else438 mapAccountBalances[""] += r.second;439 }440@@ -1208,7 +1219,7 @@441 }442 443 list<CAccountingEntry> acentries;444- CWalletDB().ListAccountCreditDebit("*", acentries);445+ CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);446 BOOST_FOREACH(const CAccountingEntry& entry, acentries)447 mapAccountBalances[entry.strAccount] += entry.nCreditDebit;448 449@@ -1230,11 +1241,11 @@450 hash.SetHex(params[0].get_str());451 452 Object entry;453- CRITICAL_BLOCK(cs_mapWallet)454- {455- if (!mapWallet.count(hash))456+ CRITICAL_BLOCK(pwalletMain->cs_mapWallet)457+ {458+ if (!pwalletMain->mapWallet.count(hash))459 throw JSONRPCError(-5, "Invalid or non-wallet transaction id");460- const CWalletTx& wtx = mapWallet[hash];461+ const CWalletTx& wtx = pwalletMain->mapWallet[hash];462 463 int64 nCredit = wtx.GetCredit();464 int64 nDebit = wtx.GetDebit();465@@ -1245,10 +1256,10 @@466 if (wtx.IsFromMe())467 entry.push_back(Pair("fee", ValueFromAmount(nFee)));468 469- WalletTxToJSON(mapWallet[hash], entry);470+ WalletTxToJSON(pwalletMain->mapWallet[hash], entry);471 472 Array details;473- ListTransactions(mapWallet[hash], "*", 0, false, details);474+ ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details);475 entry.push_back(Pair("details", details));476 }477 478@@ -1264,7 +1275,7 @@479 "Safely copies wallet.dat to destination, which can be a directory or a path with filename.");480 481 string strDest = params[0].get_str();482- BackupWallet(strDest);483+ BackupWallet(*pwalletMain, strDest);484 485 return Value::null;486 }487@@ -1290,10 +1301,10 @@488 string currentAddress = Hash160ToAddress(hash160);489 ret.push_back(Pair("address", currentAddress));490 ret.push_back(Pair("ismine", (mapPubKeys.count(hash160) > 0)));491- CRITICAL_BLOCK(cs_mapAddressBook)492- {493- if (mapAddressBook.count(currentAddress))494- ret.push_back(Pair("account", mapAddressBook[currentAddress]));495+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)496+ {497+ if (pwalletMain->mapAddressBook.count(currentAddress))498+ ret.push_back(Pair("account", pwalletMain->mapAddressBook[currentAddress]));499 }500 }501 return ret;502@@ -1320,7 +1331,7 @@503 504 static map<uint256, pair<CBlock*, unsigned int> > mapNewBlock;505 static vector<CBlock*> vNewBlock;506- static CReserveKey reservekey;507+ static CReserveKey reservekey(pwalletMain);508 509 if (params.size() == 0)510 {511@@ -1401,7 +1412,7 @@512 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);513 pblock->hashMerkleRoot = pblock->BuildMerkleTree();514 515- return CheckWork(pblock, reservekey);516+ return CheckWork(pblock, *pwalletMain, reservekey);517 }518 }519 520@@ -1526,7 +1537,7 @@521 return string(buffer);522 }523 524-string HTTPReply(int nStatus, const string& strMsg)525+static string HTTPReply(int nStatus, const string& strMsg)526 {527 if (nStatus == 401)528 return strprintf("HTTP/1.0 401 Authorization Required\r\n"529@@ -1548,6 +1559,7 @@530 string strStatus;531 if (nStatus == 200) strStatus = "OK";532 else if (nStatus == 400) strStatus = "Bad Request";533+ else if (nStatus == 403) strStatus = "Forbidden";534 else if (nStatus == 404) strStatus = "Not Found";535 else if (nStatus == 500) strStatus = "Internal Server Error";536 return strprintf(537@@ -1881,7 +1893,12 @@538 539 // Restrict callers by IP540 if (!ClientAllowed(peer.address().to_string()))541+ {542+ // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.543+ if (!fUseSSL)544+ stream << HTTPReply(403, "") << std::flush;545 continue;546+ }547 548 map<string, string> mapHeaders;549 string strRequest;
script.cpp (modified)
1--- v0.3.23/script.cpp2+++ v0.3.24/script.cpp3@@ -1021,7 +1021,7 @@4 }5 6 7-bool Solver(const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& scriptSigRet)8+bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& scriptSigRet)9 {10 scriptSigRet.clear();11 12@@ -1030,7 +1030,7 @@13 return false;14 15 // Compile solution16- CRITICAL_BLOCK(cs_mapKeys)17+ CRITICAL_BLOCK(keystore.cs_mapKeys)18 {19 BOOST_FOREACH(PAIRTYPE(opcodetype, valtype)& item, vSolution)20 {21@@ -1038,12 +1038,13 @@22 {23 // Sign24 const valtype& vchPubKey = item.second;25- if (!mapKeys.count(vchPubKey))26+ CPrivKey privkey;27+ if (!keystore.GetPrivKey(vchPubKey, privkey))28 return false;29 if (hash != 0)30 {31 vector<unsigned char> vchSig;32- if (!CKey::Sign(mapKeys[vchPubKey], hash, vchSig))33+ if (!CKey::Sign(privkey, hash, vchSig))34 return false;35 vchSig.push_back((unsigned char)nHashType);36 scriptSigRet << vchSig;37@@ -1056,12 +1057,13 @@38 if (mi == mapPubKeys.end())39 return false;40 const vector<unsigned char>& vchPubKey = (*mi).second;41- if (!mapKeys.count(vchPubKey))42+ CPrivKey privkey;43+ if (!keystore.GetPrivKey(vchPubKey, privkey))44 return false;45 if (hash != 0)46 {47 vector<unsigned char> vchSig;48- if (!CKey::Sign(mapKeys[vchPubKey], hash, vchSig))49+ if (!CKey::Sign(privkey, hash, vchSig))50 return false;51 vchSig.push_back((unsigned char)nHashType);52 scriptSigRet << vchSig << vchPubKey;53@@ -1085,14 +1087,14 @@54 }55 56 57-bool IsMine(const CScript& scriptPubKey)58+bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)59 {60 CScript scriptSig;61- return Solver(scriptPubKey, 0, 0, scriptSig);62-}63-64-65-bool ExtractPubKey(const CScript& scriptPubKey, bool fMineOnly, vector<unsigned char>& vchPubKeyRet)66+ return Solver(keystore, scriptPubKey, 0, 0, scriptSig);67+}68+69+70+bool ExtractPubKey(const CScript& scriptPubKey, const CKeyStore* keystore, vector<unsigned char>& vchPubKeyRet)71 {72 vchPubKeyRet.clear();73 74@@ -1100,7 +1102,7 @@75 if (!Solver(scriptPubKey, vSolution))76 return false;77 78- CRITICAL_BLOCK(cs_mapKeys)79+ CRITICAL_BLOCK(cs_mapPubKeys)80 {81 BOOST_FOREACH(PAIRTYPE(opcodetype, valtype)& item, vSolution)82 {83@@ -1116,7 +1118,7 @@84 continue;85 vchPubKey = (*mi).second;86 }87- if (!fMineOnly || mapKeys.count(vchPubKey))88+ if (keystore == NULL || keystore->HaveKey(vchPubKey))89 {90 vchPubKeyRet = vchPubKey;91 return true;92@@ -1160,7 +1162,7 @@93 }94 95 96-bool SignSignature(const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType, CScript scriptPrereq)97+bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType, CScript scriptPrereq)98 {99 assert(nIn < txTo.vin.size());100 CTxIn& txin = txTo.vin[nIn];101@@ -1171,7 +1173,7 @@102 // The checksig op will also drop the signatures from its hash.103 uint256 hash = SignatureHash(scriptPrereq + txout.scriptPubKey, txTo, nIn, nHashType);104 105- if (!Solver(txout.scriptPubKey, hash, nHashType, txin.scriptSig))106+ if (!Solver(keystore, txout.scriptPubKey, hash, nHashType, txin.scriptSig))107 return false;108 109 txin.scriptSig = scriptPrereq + txin.scriptSig;110@@ -1199,11 +1201,6 @@111 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, nHashType))112 return false;113 114- // Anytime a signature is successfully verified, it's proof the outpoint is spent,115- // so lets update the wallet spent flag if it doesn't know due to wallet.dat being116- // restored from backup or the user making copies of wallet.dat.117- WalletUpdateSpent(txin.prevout);118-119 return true;120 }121
script.h (modified)
1--- v0.3.23/script.h2+++ v0.3.24/script.h3@@ -5,6 +5,7 @@4 #define H_BITCOIN_SCRIPT5 6 #include "base58.h"7+#include "keystore.h"8 9 #include <string>10 #include <vector>11@@ -707,12 +708,11 @@12 13 14 15-uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);16 bool IsStandard(const CScript& scriptPubKey);17-bool IsMine(const CScript& scriptPubKey);18-bool ExtractPubKey(const CScript& scriptPubKey, bool fMineOnly, std::vector<unsigned char>& vchPubKeyRet);19+bool IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);20+bool ExtractPubKey(const CScript& scriptPubKey, const CKeyStore* pkeystore, std::vector<unsigned char>& vchPubKeyRet);21 bool ExtractHash160(const CScript& scriptPubKey, uint160& hash160Ret);22-bool SignSignature(const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL, CScript scriptPrereq=CScript());23+bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL, CScript scriptPrereq=CScript());24 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, int nHashType=0);25 26 #endif
serialize.h (modified)
1--- v0.3.23/serialize.h2+++ v0.3.24/serialize.h3@@ -33,7 +33,7 @@4 class CAutoFile;5 static const unsigned int MAX_SIZE = 0x02000000;6 7-static const int VERSION = 32300;8+static const int VERSION = 32400;9 static const char* pszSubVer = "";10 static const bool VERSION_IS_BETA = true;11
ui.cpp (modified)
1--- v0.3.23/ui.cpp2+++ v0.3.24/ui.cpp3@@ -3,6 +3,11 @@4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.5 6 #include "headers.h"7+#include "db.h"8+#include "init.h"9+#include "strlcpy.h"10+#include <boost/filesystem/fstream.hpp>11+#include <boost/filesystem/convenience.hpp>12 #ifdef _MSC_VER13 #include <crtdbg.h>14 #endif15@@ -235,7 +240,7 @@16 return;17 if (!mapPubKeys.count(hash160))18 return;19- CWalletDB().WriteDefaultKey(mapPubKeys[hash160]);20+ pwalletMain->SetDefaultKey(mapPubKeys[hash160]);21 pframeMain->m_textCtrlAddress->SetValue(strAddress);22 }23 }24@@ -285,7 +290,7 @@25 dResize = 1.22;26 SetSize(dResize * GetSize().GetWidth(), 1.15 * GetSize().GetHeight());27 #endif28- m_staticTextBalance->SetLabel(FormatMoney(GetBalance()) + " ");29+ m_staticTextBalance->SetLabel(FormatMoney(pwalletMain->GetBalance()) + " ");30 m_listCtrl->SetFocus();31 ptaskbaricon = new CMyTaskBarIcon();32 #ifdef __WXMAC_OSX__33@@ -325,7 +330,7 @@34 35 // Fill your address text box36 vector<unsigned char> vchPubKey;37- if (CWalletDB("r").ReadDefaultKey(vchPubKey))38+ if (CWalletDB(pwalletMain->strWalletFile,"r").ReadDefaultKey(vchPubKey))39 m_textCtrlAddress->SetValue(PubKeyToAddress(vchPubKey));40 41 // Fill listctrl with wallet transactions42@@ -620,7 +625,7 @@43 {44 int64 nUnmatured = 0;45 BOOST_FOREACH(const CTxOut& txout, wtx.vout)46- nUnmatured += txout.GetCredit();47+ nUnmatured += pwalletMain->GetCredit(txout);48 if (wtx.IsInMainChain())49 {50 strDescription = strprintf(_("Generated (%s matures in %d more blocks)"), FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());51@@ -656,19 +661,19 @@52 return false;53 BOOST_FOREACH(const CTxOut& txout, wtx.vout)54 {55- if (txout.IsMine())56+ if (pwalletMain->IsMine(txout))57 {58 vector<unsigned char> vchPubKey;59- if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))60+ if (ExtractPubKey(txout.scriptPubKey, pwalletMain, vchPubKey))61 {62- CRITICAL_BLOCK(cs_mapAddressBook)63+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)64 {65 //strDescription += _("Received payment to ");66 //strDescription += _("Received with address ");67 strDescription += _("Received with: ");68 string strAddress = PubKeyToAddress(vchPubKey);69- map<string, string>::iterator mi = mapAddressBook.find(strAddress);70- if (mi != mapAddressBook.end() && !(*mi).second.empty())71+ map<string, string>::iterator mi = pwalletMain->mapAddressBook.find(strAddress);72+ if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())73 {74 string strLabel = (*mi).second;75 strDescription += strAddress.substr(0,12) + "... ";76@@ -698,11 +703,11 @@77 {78 bool fAllFromMe = true;79 BOOST_FOREACH(const CTxIn& txin, wtx.vin)80- fAllFromMe = fAllFromMe && txin.IsMine();81+ fAllFromMe = fAllFromMe && pwalletMain->IsMine(txin);82 83 bool fAllToMe = true;84 BOOST_FOREACH(const CTxOut& txout, wtx.vout)85- fAllToMe = fAllToMe && txout.IsMine();86+ fAllToMe = fAllToMe && pwalletMain->IsMine(txout);87 88 if (fAllFromMe && fAllToMe)89 {90@@ -728,7 +733,7 @@91 for (int nOut = 0; nOut < wtx.vout.size(); nOut++)92 {93 const CTxOut& txout = wtx.vout[nOut];94- if (txout.IsMine())95+ if (pwalletMain->IsMine(txout))96 continue;97 98 string strAddress;99@@ -746,9 +751,9 @@100 }101 102 string strDescription = _("To: ");103- CRITICAL_BLOCK(cs_mapAddressBook)104- if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())105- strDescription += mapAddressBook[strAddress] + " ";106+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)107+ if (pwalletMain->mapAddressBook.count(strAddress) && !pwalletMain->mapAddressBook[strAddress].empty())108+ strDescription += pwalletMain->mapAddressBook[strAddress] + " ";109 strDescription += strAddress;110 if (!mapValue["message"].empty())111 {112@@ -787,9 +792,9 @@113 //114 bool fAllMine = true;115 BOOST_FOREACH(const CTxOut& txout, wtx.vout)116- fAllMine = fAllMine && txout.IsMine();117+ fAllMine = fAllMine && pwalletMain->IsMine(txout);118 BOOST_FOREACH(const CTxIn& txin, wtx.vin)119- fAllMine = fAllMine && txin.IsMine();120+ fAllMine = fAllMine && pwalletMain->IsMine(txin);121 122 InsertLine(fNew, nIndex, hash, strSort, colour,123 strStatus,124@@ -816,16 +821,16 @@125 // Collect list of wallet transactions and sort newest first126 bool fEntered = false;127 vector<pair<unsigned int, uint256> > vSorted;128- TRY_CRITICAL_BLOCK(cs_mapWallet)129+ TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)130 {131 printf("RefreshListCtrl starting\n");132 fEntered = true;133 fRefreshListCtrl = false;134- vWalletUpdated.clear();135+ pwalletMain->vWalletUpdated.clear();136 137 // Do the newest transactions first138- vSorted.reserve(mapWallet.size());139- for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)140+ vSorted.reserve(pwalletMain->mapWallet.size());141+ for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)142 {143 const CWalletTx& wtx = (*it).second;144 unsigned int nTime = UINT_MAX - wtx.GetTxTime();145@@ -844,12 +849,12 @@146 if (fShutdown)147 return;148 bool fEntered = false;149- TRY_CRITICAL_BLOCK(cs_mapWallet)150+ TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)151 {152 fEntered = true;153 uint256& hash = vSorted[i++].second;154- map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);155- if (mi != mapWallet.end())156+ map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);157+ if (mi != pwalletMain->mapWallet.end())158 InsertTransaction((*mi).second, true);159 }160 if (!fEntered || i == 100 || i % 500 == 0)161@@ -867,10 +872,10 @@162 static int64 nLastTime;163 if (GetTime() > nLastTime + 30)164 {165- TRY_CRITICAL_BLOCK(cs_mapWallet)166+ TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)167 {168 nLastTime = GetTime();169- for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)170+ for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)171 {172 CWalletTx& wtx = (*it).second;173 if (wtx.nTimeDisplayed && wtx.nTimeDisplayed != wtx.GetTxTime())174@@ -891,7 +896,7 @@175 if (nTop == nLastTop && pindexLastBest == pindexBest)176 return;177 178- TRY_CRITICAL_BLOCK(cs_mapWallet)179+ TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)180 {181 int nStart = nTop;182 int nEnd = min(nStart + 100, m_listCtrl->GetItemCount());183@@ -911,8 +916,8 @@184 for (int nIndex = nStart; nIndex < min(nEnd, m_listCtrl->GetItemCount()); nIndex++)185 {186 uint256 hash((string)GetItemText(m_listCtrl, nIndex, 1));187- map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);188- if (mi == mapWallet.end())189+ map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);190+ if (mi == pwalletMain->mapWallet.end())191 {192 printf("CMainFrame::RefreshStatusColumn() : tx not found in mapWallet\n");193 continue;194@@ -1009,41 +1014,41 @@195 nLastRepaintTime = GetTimeMillis();196 197 // Update listctrl contents198- if (!vWalletUpdated.empty())199- {200- TRY_CRITICAL_BLOCK(cs_mapWallet)201+ if (!pwalletMain->vWalletUpdated.empty())202+ {203+ TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)204 {205 string strTop;206 if (m_listCtrl->GetItemCount())207 strTop = (string)m_listCtrl->GetItemText(0);208- BOOST_FOREACH(uint256 hash, vWalletUpdated)209+ BOOST_FOREACH(uint256 hash, pwalletMain->vWalletUpdated)210 {211- map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);212- if (mi != mapWallet.end())213+ map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);214+ if (mi != pwalletMain->mapWallet.end())215 InsertTransaction((*mi).second, false);216 }217- vWalletUpdated.clear();218+ pwalletMain->vWalletUpdated.clear();219 if (m_listCtrl->GetItemCount() && strTop != (string)m_listCtrl->GetItemText(0))220 m_listCtrl->ScrollList(0, INT_MIN/2);221 }222 }223 224 // Balance total225- TRY_CRITICAL_BLOCK(cs_mapWallet)226+ TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)227 {228 fPaintedBalance = true;229- m_staticTextBalance->SetLabel(FormatMoney(GetBalance()) + " ");230+ m_staticTextBalance->SetLabel(FormatMoney(pwalletMain->GetBalance()) + " ");231 232 // Count hidden and multi-line transactions233 nTransactionCount = 0;234- for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)235+ for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)236 {237 CWalletTx& wtx = (*it).second;238 nTransactionCount += wtx.nLinesDisplayed;239 }240 }241 }242- if (!vWalletUpdated.empty() || !fPaintedBalance)243+ if (!pwalletMain->vWalletUpdated.empty() || !fPaintedBalance)244 nNeedRepaint++;245 246 // Update status column of visible items only247@@ -1069,7 +1074,7 @@248 m_statusBar->SetStatusText(strStatus, 2);249 250 // Update receiving address251- string strDefaultAddress = PubKeyToAddress(vchDefaultKey);252+ string strDefaultAddress = PubKeyToAddress(pwalletMain->vchDefaultKey);253 if (m_textCtrlAddress->GetValue() != strDefaultAddress)254 m_textCtrlAddress->SetValue(strDefaultAddress);255 }256@@ -1178,10 +1183,11 @@257 string strName = dialog.GetValue();258 259 // Generate new key260- string strAddress = PubKeyToAddress(GetKeyFromKeyPool());261+ string strAddress = PubKeyToAddress(pwalletMain->GetKeyFromKeyPool());262 263 // Save264- SetAddressBookName(strAddress, strName);265+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)266+ pwalletMain->SetAddressBookName(strAddress, strName);267 SetDefaultReceivingAddress(strAddress);268 }269 270@@ -1199,10 +1205,10 @@271 {272 uint256 hash((string)GetItemText(m_listCtrl, event.GetIndex(), 1));273 CWalletTx wtx;274- CRITICAL_BLOCK(cs_mapWallet)275- {276- map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);277- if (mi == mapWallet.end())278+ CRITICAL_BLOCK(pwalletMain->cs_mapWallet)279+ {280+ map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);281+ if (mi == pwalletMain->mapWallet.end())282 {283 printf("CMainFrame::OnListItemActivated() : tx not found in mapWallet\n");284 return;285@@ -1230,7 +1236,7 @@286 #ifdef __WXMSW__287 SetSize(nScaleX * GetSize().GetWidth(), nScaleY * GetSize().GetHeight());288 #endif289- CRITICAL_BLOCK(cs_mapAddressBook)290+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)291 {292 string strHTML;293 strHTML.reserve(4000);294@@ -1280,19 +1286,19 @@295 // Credit296 BOOST_FOREACH(const CTxOut& txout, wtx.vout)297 {298- if (txout.IsMine())299+ if (pwalletMain->IsMine(txout))300 {301 vector<unsigned char> vchPubKey;302- if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))303+ if (ExtractPubKey(txout.scriptPubKey, pwalletMain, vchPubKey))304 {305 string strAddress = PubKeyToAddress(vchPubKey);306- if (mapAddressBook.count(strAddress))307+ if (pwalletMain->mapAddressBook.count(strAddress))308 {309 strHTML += string() + _("<b>From:</b> ") + _("unknown") + "<br>";310 strHTML += _("<b>To:</b> ");311 strHTML += HtmlEscape(strAddress);312- if (!mapAddressBook[strAddress].empty())313- strHTML += _(" (yours, label: ") + mapAddressBook[strAddress] + ")";314+ if (!pwalletMain->mapAddressBook[strAddress].empty())315+ strHTML += _(" (yours, label: ") + pwalletMain->mapAddressBook[strAddress] + ")";316 else317 strHTML += _(" (yours)");318 strHTML += "<br>";319@@ -1314,8 +1320,8 @@320 // Online transaction321 strAddress = wtx.mapValue["to"];322 strHTML += _("<b>To:</b> ");323- if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())324- strHTML += mapAddressBook[strAddress] + " ";325+ if (pwalletMain->mapAddressBook.count(strAddress) && !pwalletMain->mapAddressBook[strAddress].empty())326+ strHTML += pwalletMain->mapAddressBook[strAddress] + " ";327 strHTML += HtmlEscape(strAddress) + "<br>";328 }329 330@@ -1330,7 +1336,7 @@331 //332 int64 nUnmatured = 0;333 BOOST_FOREACH(const CTxOut& txout, wtx.vout)334- nUnmatured += txout.GetCredit();335+ nUnmatured += pwalletMain->GetCredit(txout);336 strHTML += _("<b>Credit:</b> ");337 if (wtx.IsInMainChain())338 strHTML += strprintf(_("(%s matures in %d more blocks)"), FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());339@@ -1349,11 +1355,11 @@340 {341 bool fAllFromMe = true;342 BOOST_FOREACH(const CTxIn& txin, wtx.vin)343- fAllFromMe = fAllFromMe && txin.IsMine();344+ fAllFromMe = fAllFromMe && pwalletMain->IsMine(txin);345 346 bool fAllToMe = true;347 BOOST_FOREACH(const CTxOut& txout, wtx.vout)348- fAllToMe = fAllToMe && txout.IsMine();349+ fAllToMe = fAllToMe && pwalletMain->IsMine(txout);350 351 if (fAllFromMe)352 {353@@ -1362,7 +1368,7 @@354 //355 BOOST_FOREACH(const CTxOut& txout, wtx.vout)356 {357- if (txout.IsMine())358+ if (pwalletMain->IsMine(txout))359 continue;360 361 if (wtx.mapValue["to"].empty())362@@ -1373,8 +1379,8 @@363 {364 string strAddress = Hash160ToAddress(hash160);365 strHTML += _("<b>To:</b> ");366- if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())367- strHTML += mapAddressBook[strAddress] + " ";368+ if (pwalletMain->mapAddressBook.count(strAddress) && !pwalletMain->mapAddressBook[strAddress].empty())369+ strHTML += pwalletMain->mapAddressBook[strAddress] + " ";370 strHTML += strAddress;371 strHTML += "<br>";372 }373@@ -1402,11 +1408,11 @@374 // Mixed debit transaction375 //376 BOOST_FOREACH(const CTxIn& txin, wtx.vin)377- if (txin.IsMine())378- strHTML += _("<b>Debit:</b> ") + FormatMoney(-txin.GetDebit()) + "<br>";379+ if (pwalletMain->IsMine(txin))380+ strHTML += _("<b>Debit:</b> ") + FormatMoney(-pwalletMain->GetDebit(txin)) + "<br>";381 BOOST_FOREACH(const CTxOut& txout, wtx.vout)382- if (txout.IsMine())383- strHTML += _("<b>Credit:</b> ") + FormatMoney(txout.GetCredit()) + "<br>";384+ if (pwalletMain->IsMine(txout))385+ strHTML += _("<b>Credit:</b> ") + FormatMoney(pwalletMain->GetCredit(txout)) + "<br>";386 }387 }388 389@@ -1432,30 +1438,30 @@390 {391 strHTML += "<hr><br>debug print<br><br>";392 BOOST_FOREACH(const CTxIn& txin, wtx.vin)393- if (txin.IsMine())394- strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>";395+ if (pwalletMain->IsMine(txin))396+ strHTML += "<b>Debit:</b> " + FormatMoney(-pwalletMain->GetDebit(txin)) + "<br>";397 BOOST_FOREACH(const CTxOut& txout, wtx.vout)398- if (txout.IsMine())399- strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";400+ if (pwalletMain->IsMine(txout))401+ strHTML += "<b>Credit:</b> " + FormatMoney(pwalletMain->GetCredit(txout)) + "<br>";402 403 strHTML += "<br><b>Transaction:</b><br>";404 strHTML += HtmlEscape(wtx.ToString(), true);405 406 strHTML += "<br><b>Inputs:</b><br>";407- CRITICAL_BLOCK(cs_mapWallet)408+ CRITICAL_BLOCK(pwalletMain->cs_mapWallet)409 {410 BOOST_FOREACH(const CTxIn& txin, wtx.vin)411 {412 COutPoint prevout = txin.prevout;413- map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);414- if (mi != mapWallet.end())415+ map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(prevout.hash);416+ if (mi != pwalletMain->mapWallet.end())417 {418 const CWalletTx& prev = (*mi).second;419 if (prevout.n < prev.vout.size())420 {421 strHTML += HtmlEscape(prev.ToString(), true);422 strHTML += " " + FormatTxStatus(prev) + ", ";423- strHTML = strHTML + "IsMine=" + (prev.vout[prevout.n].IsMine() ? "true" : "false") + "<br>";424+ strHTML = strHTML + "IsMine=" + (pwalletMain->IsMine(prev.vout[prevout.n]) ? "true" : "false") + "<br>";425 }426 }427 }428@@ -1746,7 +1752,7 @@429 430 void COptionsDialog::OnButtonApply(wxCommandEvent& event)431 {432- CWalletDB walletdb;433+ CWalletDB walletdb(pwalletMain->strWalletFile);434 435 int64 nPrevTransactionFee = nTransactionFee;436 if (ParseMoney(m_textCtrlTransactionFee->GetValue(), nTransactionFee) && nTransactionFee != nPrevTransactionFee)437@@ -1923,12 +1929,12 @@438 wxMessageBox(_("Error in amount "), _("Send Coins"));439 return;440 }441- if (nValue > GetBalance())442+ if (nValue > pwalletMain->GetBalance())443 {444 wxMessageBox(_("Amount exceeds your balance "), _("Send Coins"));445 return;446 }447- if (nValue + nTransactionFee > GetBalance())448+ if (nValue + nTransactionFee > pwalletMain->GetBalance())449 {450 wxMessageBox(string(_("Total exceeds your balance when the ")) + FormatMoney(nTransactionFee) + _(" transaction fee is included "), _("Send Coins"));451 return;452@@ -1946,7 +1952,7 @@453 CScript scriptPubKey;454 scriptPubKey << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;455 456- string strError = SendMoney(scriptPubKey, nValue, wtx, true);457+ string strError = pwalletMain->SendMoney(scriptPubKey, nValue, wtx, true);458 if (strError == "")459 wxMessageBox(_("Payment sent "), _("Sending..."));460 else if (strError == "ABORTED")461@@ -1978,9 +1984,9 @@462 return;463 }464 465- CRITICAL_BLOCK(cs_mapAddressBook)466- if (!mapAddressBook.count(strAddress))467- SetAddressBookName(strAddress, "");468+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)469+ if (!pwalletMain->mapAddressBook.count(strAddress))470+ pwalletMain->SetAddressBookName(strAddress, "");471 472 EndModal(true);473 }474@@ -2164,7 +2170,7 @@475 void CSendingDialog::StartTransfer()476 {477 // Make sure we have enough money478- if (nPrice + nTransactionFee > GetBalance())479+ if (nPrice + nTransactionFee > pwalletMain->GetBalance())480 {481 Error(_("Insufficient funds"));482 return;483@@ -2235,16 +2241,16 @@484 // Pay485 if (!Status(_("Creating transaction...")))486 return;487- if (nPrice + nTransactionFee > GetBalance())488+ if (nPrice + nTransactionFee > pwalletMain->GetBalance())489 {490 Error(_("Insufficient funds"));491 return;492 }493- CReserveKey reservekey;494+ CReserveKey reservekey(pwalletMain);495 int64 nFeeRequired;496- if (!CreateTransaction(scriptPubKey, nPrice, wtx, reservekey, nFeeRequired))497- {498- if (nPrice + nFeeRequired > GetBalance())499+ if (!pwalletMain->CreateTransaction(scriptPubKey, nPrice, wtx, reservekey, nFeeRequired))500+ {501+ if (nPrice + nFeeRequired > pwalletMain->GetBalance())502 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()));503 else504 Error(_("Transaction creation failed"));505@@ -2282,7 +2288,7 @@506 return;507 508 // Commit509- if (!CommitTransaction(wtx, reservekey))510+ if (!pwalletMain->CommitTransaction(wtx, reservekey))511 {512 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."));513 return;514@@ -2376,11 +2382,11 @@515 m_listCtrlReceiving->SetFocus();516 517 // Fill listctrl with address book data518- CRITICAL_BLOCK(cs_mapKeys)519- CRITICAL_BLOCK(cs_mapAddressBook)520+ CRITICAL_BLOCK(pwalletMain->cs_mapKeys)521+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)522 {523 string strDefaultReceiving = (string)pframeMain->m_textCtrlAddress->GetValue();524- BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)525+ BOOST_FOREACH(const PAIRTYPE(string, string)& item, pwalletMain->mapAddressBook)526 {527 string strAddress = item.first;528 string strName = item.second;529@@ -2439,7 +2445,8 @@530 if (event.IsEditCancelled())531 return;532 string strAddress = (string)GetItemText(m_listCtrl, event.GetIndex(), 1);533- SetAddressBookName(strAddress, string(event.GetText()));534+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)535+ pwalletMain->SetAddressBookName(strAddress, string(event.GetText()));536 pframeMain->RefreshListCtrl();537 }538 539@@ -2474,7 +2481,8 @@540 if (m_listCtrl->GetItemState(nIndex, wxLIST_STATE_SELECTED))541 {542 string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);543- CWalletDB().EraseName(strAddress);544+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)545+ pwalletMain->DelAddressBookName(strAddress);546 m_listCtrl->DeleteItem(nIndex);547 }548 }549@@ -2533,9 +2541,12 @@550 }551 552 // Write back553- if (strAddress != strAddressOrg)554- CWalletDB().EraseName(strAddressOrg);555- SetAddressBookName(strAddress, strName);556+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)557+ {558+ if (strAddress != strAddressOrg)559+ pwalletMain->DelAddressBookName(strAddressOrg);560+ pwalletMain->SetAddressBookName(strAddress, strName);561+ }562 m_listCtrl->SetItem(nIndex, 1, strAddress);563 m_listCtrl->SetItemText(nIndex, strName);564 pframeMain->RefreshListCtrl();565@@ -2571,11 +2582,12 @@566 strName = dialog.GetValue();567 568 // Generate new key569- strAddress = PubKeyToAddress(GetKeyFromKeyPool());570+ strAddress = PubKeyToAddress(pwalletMain->GetKeyFromKeyPool());571 }572 573 // Add to list and select it574- SetAddressBookName(strAddress, strName);575+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)576+ pwalletMain->SetAddressBookName(strAddress, strName);577 int nIndex = InsertLine(m_listCtrl, strName, strAddress);578 SetSelection(m_listCtrl, nIndex);579 m_listCtrl->SetFocus();
ui.h (modified)
1--- v0.3.23/ui.h2+++ v0.3.24/ui.h3@@ -3,6 +3,9 @@4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.5 #ifndef BITCOIN_UI_H6 #define BITCOIN_UI_H7+8+#include <boost/function.hpp>9+#include "wallet.h"10 11 DECLARE_EVENT_TYPE(wxEVT_UITHREADCALL, -1)12
util.cpp (modified)
1--- v0.3.23/util.cpp2+++ v0.3.24/util.cpp3@@ -2,6 +2,14 @@4 // Distributed under the MIT/X11 software license, see the accompanying5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.6 #include "headers.h"7+#include "strlcpy.h"8+#include <boost/program_options/detail/config_file.hpp>9+#include <boost/program_options/parsers.hpp>10+#include <boost/filesystem.hpp>11+#include <boost/filesystem/fstream.hpp>12+#include <boost/interprocess/sync/interprocess_mutex.hpp>13+#include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>14+#include <boost/foreach.hpp>15 16 using namespace std;17 using namespace boost;18@@ -338,11 +346,6 @@19 if (nTrim)20 str.erase(str.size()-nTrim, nTrim);21 22- // Insert thousands-separators:23- size_t point = str.find(".");24- for (int i = (str.size()-point)+3; i < str.size(); i += 4)25- if (isdigit(str[str.size() - i - 1]))26- str.insert(str.size() - i, 1, ',');27 if (n < 0)28 str.insert((unsigned int)0, 1, '-');29 else if (fPlus && n > 0)30@@ -365,8 +368,6 @@31 p++;32 for (; *p; p++)33 {34- if (*p == ',' && p > pszIn && isdigit(p[-1]) && isdigit(p[1]) && isdigit(p[2]) && isdigit(p[3]) && !isdigit(p[4]))35- continue;36 if (*p == '.')37 {38 p++;39@@ -895,8 +896,10 @@40 string FormatFullVersion()41 {42 string s = FormatVersion(VERSION) + pszSubVer;43- if (VERSION_IS_BETA)44- s += _("-beta");45+ if (VERSION_IS_BETA) {46+ s += "-";47+ s += _("beta");48+ }49 return s;50 }51
util.h (modified)
1--- v0.3.23/util.h2+++ v0.3.24/util.h3@@ -15,7 +15,6 @@4 #include <vector>5 #include <string>6 7-#include <boost/foreach.hpp>8 #include <boost/thread.hpp>9 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>10 #include <boost/date_time/gregorian/gregorian_types.hpp>
wallet.cpp (added)
1--- /dev/null2+++ v0.3.24/wallet.cpp3@@ -1 +1,1140 @@4-5+// Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers6+// Distributed under the MIT/X11 software license, see the accompanying7+// file license.txt or http://www.opensource.org/licenses/mit-license.php.8+9+#include "headers.h"10+#include "db.h"11+#include "cryptopp/sha.h"12+13+using namespace std;14+15+16+17+//////////////////////////////////////////////////////////////////////////////18+//19+// mapWallet20+//21+22+bool CWallet::AddKey(const CKey& key)23+{24+ this->CKeyStore::AddKey(key);25+ if (!fFileBacked)26+ return true;27+ return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());28+}29+30+void CWallet::WalletUpdateSpent(const CTransaction &tx)31+{32+ // Anytime a signature is successfully verified, it's proof the outpoint is spent.33+ // Update the wallet spent flag if it doesn't know due to wallet.dat being34+ // restored from backup or the user making copies of wallet.dat.35+ CRITICAL_BLOCK(cs_mapWallet)36+ {37+ BOOST_FOREACH(const CTxIn& txin, tx.vin)38+ {39+ map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);40+ if (mi != mapWallet.end())41+ {42+ CWalletTx& wtx = (*mi).second;43+ if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))44+ {45+ printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());46+ wtx.MarkSpent(txin.prevout.n);47+ wtx.WriteToDisk();48+ vWalletUpdated.push_back(txin.prevout.hash);49+ }50+ }51+ }52+ }53+}54+55+bool CWallet::AddToWallet(const CWalletTx& wtxIn)56+{57+ uint256 hash = wtxIn.GetHash();58+ CRITICAL_BLOCK(cs_mapWallet)59+ {60+ // Inserts only if not already there, returns tx inserted or tx found61+ pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));62+ CWalletTx& wtx = (*ret.first).second;63+ wtx.pwallet = this;64+ bool fInsertedNew = ret.second;65+ if (fInsertedNew)66+ wtx.nTimeReceived = GetAdjustedTime();67+68+ bool fUpdated = false;69+ if (!fInsertedNew)70+ {71+ // Merge72+ if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)73+ {74+ wtx.hashBlock = wtxIn.hashBlock;75+ fUpdated = true;76+ }77+ if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))78+ {79+ wtx.vMerkleBranch = wtxIn.vMerkleBranch;80+ wtx.nIndex = wtxIn.nIndex;81+ fUpdated = true;82+ }83+ if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)84+ {85+ wtx.fFromMe = wtxIn.fFromMe;86+ fUpdated = true;87+ }88+ fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);89+ }90+91+ //// debug print92+ printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));93+94+ // Write to disk95+ if (fInsertedNew || fUpdated)96+ if (!wtx.WriteToDisk())97+ return false;98+99+ // If default receiving address gets used, replace it with a new one100+ CScript scriptDefaultKey;101+ scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);102+ BOOST_FOREACH(const CTxOut& txout, wtx.vout)103+ {104+ if (txout.scriptPubKey == scriptDefaultKey)105+ SetDefaultKey(GetKeyFromKeyPool());106+ }107+108+ // Notify UI109+ vWalletUpdated.push_back(hash);110+111+ // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins112+ WalletUpdateSpent(wtx);113+ }114+115+ // Refresh UI116+ MainFrameRepaint();117+ return true;118+}119+120+bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)121+{122+ uint256 hash = tx.GetHash();123+ bool fExisted = mapWallet.count(hash);124+ if (fExisted && !fUpdate) return false;125+ if (fExisted || IsMine(tx) || IsFromMe(tx))126+ {127+ CWalletTx wtx(this,tx);128+ // Get merkle branch if transaction was found in a block129+ if (pblock)130+ wtx.SetMerkleBranch(pblock);131+ return AddToWallet(wtx);132+ }133+ else134+ WalletUpdateSpent(tx);135+ return false;136+}137+138+bool CWallet::EraseFromWallet(uint256 hash)139+{140+ if (!fFileBacked)141+ return false;142+ CRITICAL_BLOCK(cs_mapWallet)143+ {144+ if (mapWallet.erase(hash))145+ CWalletDB(strWalletFile).EraseTx(hash);146+ }147+ return true;148+}149+150+151+bool CWallet::IsMine(const CTxIn &txin) const152+{153+ CRITICAL_BLOCK(cs_mapWallet)154+ {155+ map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);156+ if (mi != mapWallet.end())157+ {158+ const CWalletTx& prev = (*mi).second;159+ if (txin.prevout.n < prev.vout.size())160+ if (IsMine(prev.vout[txin.prevout.n]))161+ return true;162+ }163+ }164+ return false;165+}166+167+int64 CWallet::GetDebit(const CTxIn &txin) const168+{169+ CRITICAL_BLOCK(cs_mapWallet)170+ {171+ map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);172+ if (mi != mapWallet.end())173+ {174+ const CWalletTx& prev = (*mi).second;175+ if (txin.prevout.n < prev.vout.size())176+ if (IsMine(prev.vout[txin.prevout.n]))177+ return prev.vout[txin.prevout.n].nValue;178+ }179+ }180+ return 0;181+}182+183+int64 CWalletTx::GetTxTime() const184+{185+ if (!fTimeReceivedIsTxTime && hashBlock != 0)186+ {187+ // If we did not receive the transaction directly, we rely on the block's188+ // time to figure out when it happened. We use the median over a range189+ // of blocks to try to filter out inaccurate block times.190+ map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);191+ if (mi != mapBlockIndex.end())192+ {193+ CBlockIndex* pindex = (*mi).second;194+ if (pindex)195+ return pindex->GetMedianTime();196+ }197+ }198+ return nTimeReceived;199+}200+201+int CWalletTx::GetRequestCount() const202+{203+ // Returns -1 if it wasn't being tracked204+ int nRequests = -1;205+ CRITICAL_BLOCK(pwallet->cs_mapRequestCount)206+ {207+ if (IsCoinBase())208+ {209+ // Generated block210+ if (hashBlock != 0)211+ {212+ map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);213+ if (mi != pwallet->mapRequestCount.end())214+ nRequests = (*mi).second;215+ }216+ }217+ else218+ {219+ // Did anyone request this transaction?220+ map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());221+ if (mi != pwallet->mapRequestCount.end())222+ {223+ nRequests = (*mi).second;224+225+ // How about the block it's in?226+ if (nRequests == 0 && hashBlock != 0)227+ {228+ map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);229+ if (mi != pwallet->mapRequestCount.end())230+ nRequests = (*mi).second;231+ else232+ nRequests = 1; // If it's in someone else's block it must have got out233+ }234+ }235+ }236+ }237+ return nRequests;238+}239+240+void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string, int64> >& listReceived,241+ list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const242+{243+ nGeneratedImmature = nGeneratedMature = nFee = 0;244+ listReceived.clear();245+ listSent.clear();246+ strSentAccount = strFromAccount;247+248+ if (IsCoinBase())249+ {250+ if (GetBlocksToMaturity() > 0)251+ nGeneratedImmature = pwallet->GetCredit(*this);252+ else253+ nGeneratedMature = GetCredit();254+ return;255+ }256+257+ // Compute fee:258+ int64 nDebit = GetDebit();259+ if (nDebit > 0) // debit>0 means we signed/sent this transaction260+ {261+ int64 nValueOut = GetValueOut();262+ nFee = nDebit - nValueOut;263+ }264+265+ // Sent/received. Standard client will never generate a send-to-multiple-recipients,266+ // but non-standard clients might (so return a list of address/amount pairs)267+ BOOST_FOREACH(const CTxOut& txout, vout)268+ {269+ string address;270+ uint160 hash160;271+ vector<unsigned char> vchPubKey;272+ if (ExtractHash160(txout.scriptPubKey, hash160))273+ address = Hash160ToAddress(hash160);274+ else if (ExtractPubKey(txout.scriptPubKey, NULL, vchPubKey))275+ address = PubKeyToAddress(vchPubKey);276+ else277+ {278+ printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",279+ this->GetHash().ToString().c_str());280+ address = " unknown ";281+ }282+283+ // Don't report 'change' txouts284+ if (nDebit > 0 && pwallet->IsChange(txout))285+ continue;286+287+ if (nDebit > 0)288+ listSent.push_back(make_pair(address, txout.nValue));289+290+ if (pwallet->IsMine(txout))291+ listReceived.push_back(make_pair(address, txout.nValue));292+ }293+294+}295+296+void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived, 297+ int64& nSent, int64& nFee) const298+{299+ nGenerated = nReceived = nSent = nFee = 0;300+301+ int64 allGeneratedImmature, allGeneratedMature, allFee;302+ allGeneratedImmature = allGeneratedMature = allFee = 0;303+ string strSentAccount;304+ list<pair<string, int64> > listReceived;305+ list<pair<string, int64> > listSent;306+ GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);307+308+ if (strAccount == "")309+ nGenerated = allGeneratedMature;310+ if (strAccount == strSentAccount)311+ {312+ BOOST_FOREACH(const PAIRTYPE(string,int64)& s, listSent)313+ nSent += s.second;314+ nFee = allFee;315+ }316+ CRITICAL_BLOCK(pwallet->cs_mapAddressBook)317+ {318+ BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)319+ {320+ if (pwallet->mapAddressBook.count(r.first))321+ {322+ map<string, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);323+ if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)324+ nReceived += r.second;325+ }326+ else if (strAccount.empty())327+ {328+ nReceived += r.second;329+ }330+ }331+ }332+}333+334+void CWalletTx::AddSupportingTransactions(CTxDB& txdb)335+{336+ vtxPrev.clear();337+338+ const int COPY_DEPTH = 3;339+ if (SetMerkleBranch() < COPY_DEPTH)340+ {341+ vector<uint256> vWorkQueue;342+ BOOST_FOREACH(const CTxIn& txin, vin)343+ vWorkQueue.push_back(txin.prevout.hash);344+345+ // This critsect is OK because txdb is already open346+ CRITICAL_BLOCK(pwallet->cs_mapWallet)347+ {348+ map<uint256, const CMerkleTx*> mapWalletPrev;349+ set<uint256> setAlreadyDone;350+ for (int i = 0; i < vWorkQueue.size(); i++)351+ {352+ uint256 hash = vWorkQueue[i];353+ if (setAlreadyDone.count(hash))354+ continue;355+ setAlreadyDone.insert(hash);356+357+ CMerkleTx tx;358+ map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);359+ if (mi != pwallet->mapWallet.end())360+ {361+ tx = (*mi).second;362+ BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)363+ mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;364+ }365+ else if (mapWalletPrev.count(hash))366+ {367+ tx = *mapWalletPrev[hash];368+ }369+ else if (!fClient && txdb.ReadDiskTx(hash, tx))370+ {371+ ;372+ }373+ else374+ {375+ printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");376+ continue;377+ }378+379+ int nDepth = tx.SetMerkleBranch();380+ vtxPrev.push_back(tx);381+382+ if (nDepth < COPY_DEPTH)383+ BOOST_FOREACH(const CTxIn& txin, tx.vin)384+ vWorkQueue.push_back(txin.prevout.hash);385+ }386+ }387+ }388+389+ reverse(vtxPrev.begin(), vtxPrev.end());390+}391+392+bool CWalletTx::WriteToDisk()393+{394+ return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);395+}396+397+int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)398+{399+ int ret = 0;400+401+ CBlockIndex* pindex = pindexStart;402+ CRITICAL_BLOCK(cs_mapWallet)403+ {404+ while (pindex)405+ {406+ CBlock block;407+ block.ReadFromDisk(pindex, true);408+ BOOST_FOREACH(CTransaction& tx, block.vtx)409+ {410+ if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))411+ ret++;412+ }413+ pindex = pindex->pnext;414+ }415+ }416+ return ret;417+}418+419+void CWallet::ReacceptWalletTransactions()420+{421+ CTxDB txdb("r");422+ bool fRepeat = true;423+ while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)424+ {425+ fRepeat = false;426+ vector<CDiskTxPos> vMissingTx;427+ BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)428+ {429+ CWalletTx& wtx = item.second;430+ if (wtx.IsCoinBase() && wtx.IsSpent(0))431+ continue;432+433+ CTxIndex txindex;434+ bool fUpdated = false;435+ if (txdb.ReadTxIndex(wtx.GetHash(), txindex))436+ {437+ // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat438+ if (txindex.vSpent.size() != wtx.vout.size())439+ {440+ printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());441+ continue;442+ }443+ for (int i = 0; i < txindex.vSpent.size(); i++)444+ {445+ if (wtx.IsSpent(i))446+ continue;447+ if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))448+ {449+ wtx.MarkSpent(i);450+ fUpdated = true;451+ vMissingTx.push_back(txindex.vSpent[i]);452+ }453+ }454+ if (fUpdated)455+ {456+ printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());457+ wtx.MarkDirty();458+ wtx.WriteToDisk();459+ }460+ }461+ else462+ {463+ // Reaccept any txes of ours that aren't already in a block464+ if (!wtx.IsCoinBase())465+ wtx.AcceptWalletTransaction(txdb, false);466+ }467+ }468+ if (!vMissingTx.empty())469+ {470+ // TODO: optimize this to scan just part of the block chain?471+ if (ScanForWalletTransactions(pindexGenesisBlock))472+ fRepeat = true; // Found missing transactions: re-do Reaccept.473+ }474+ }475+}476+477+void CWalletTx::RelayWalletTransaction(CTxDB& txdb)478+{479+ BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)480+ {481+ if (!tx.IsCoinBase())482+ {483+ uint256 hash = tx.GetHash();484+ if (!txdb.ContainsTx(hash))485+ RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);486+ }487+ }488+ if (!IsCoinBase())489+ {490+ uint256 hash = GetHash();491+ if (!txdb.ContainsTx(hash))492+ {493+ printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());494+ RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);495+ }496+ }497+}498+499+void CWalletTx::RelayWalletTransaction()500+{501+ CTxDB txdb("r");502+ RelayWalletTransaction(txdb);503+}504+505+void CWallet::ResendWalletTransactions()506+{507+ // Do this infrequently and randomly to avoid giving away508+ // that these are our transactions.509+ static int64 nNextTime;510+ if (GetTime() < nNextTime)511+ return;512+ bool fFirst = (nNextTime == 0);513+ nNextTime = GetTime() + GetRand(30 * 60);514+ if (fFirst)515+ return;516+517+ // Only do it if there's been a new block since last time518+ static int64 nLastTime;519+ if (nTimeBestReceived < nLastTime)520+ return;521+ nLastTime = GetTime();522+523+ // Rebroadcast any of our txes that aren't in a block yet524+ printf("ResendWalletTransactions()\n");525+ CTxDB txdb("r");526+ CRITICAL_BLOCK(cs_mapWallet)527+ {528+ // Sort them in chronological order529+ multimap<unsigned int, CWalletTx*> mapSorted;530+ BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)531+ {532+ CWalletTx& wtx = item.second;533+ // Don't rebroadcast until it's had plenty of time that534+ // it should have gotten in already by now.535+ if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)536+ mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));537+ }538+ BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)539+ {540+ CWalletTx& wtx = *item.second;541+ wtx.RelayWalletTransaction(txdb);542+ }543+ }544+}545+546+547+548+549+550+551+//////////////////////////////////////////////////////////////////////////////552+//553+// Actions554+//555+556+557+int64 CWallet::GetBalance() const558+{559+ int64 nStart = GetTimeMillis();560+561+ int64 nTotal = 0;562+ CRITICAL_BLOCK(cs_mapWallet)563+ {564+ for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)565+ {566+ const CWalletTx* pcoin = &(*it).second;567+ if (!pcoin->IsFinal() || !pcoin->IsConfirmed())568+ continue;569+ nTotal += pcoin->GetAvailableCredit();570+ }571+ }572+573+ //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);574+ return nTotal;575+}576+577+578+bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const579+{580+ setCoinsRet.clear();581+ nValueRet = 0;582+583+ // List of values less than target584+ pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;585+ coinLowestLarger.first = INT64_MAX;586+ coinLowestLarger.second.first = NULL;587+ vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;588+ int64 nTotalLower = 0;589+590+ CRITICAL_BLOCK(cs_mapWallet)591+ {592+ vector<const CWalletTx*> vCoins;593+ vCoins.reserve(mapWallet.size());594+ for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)595+ vCoins.push_back(&(*it).second);596+ random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);597+598+ BOOST_FOREACH(const CWalletTx* pcoin, vCoins)599+ {600+ if (!pcoin->IsFinal() || !pcoin->IsConfirmed())601+ continue;602+603+ if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)604+ continue;605+606+ int nDepth = pcoin->GetDepthInMainChain();607+ if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))608+ continue;609+610+ for (int i = 0; i < pcoin->vout.size(); i++)611+ {612+ if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))613+ continue;614+615+ int64 n = pcoin->vout[i].nValue;616+617+ if (n <= 0)618+ continue;619+620+ pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));621+622+ if (n == nTargetValue)623+ {624+ setCoinsRet.insert(coin.second);625+ nValueRet += coin.first;626+ return true;627+ }628+ else if (n < nTargetValue + CENT)629+ {630+ vValue.push_back(coin);631+ nTotalLower += n;632+ }633+ else if (n < coinLowestLarger.first)634+ {635+ coinLowestLarger = coin;636+ }637+ }638+ }639+ }640+641+ if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)642+ {643+ for (int i = 0; i < vValue.size(); ++i)644+ {645+ setCoinsRet.insert(vValue[i].second);646+ nValueRet += vValue[i].first;647+ }648+ return true;649+ }650+651+ if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))652+ {653+ if (coinLowestLarger.second.first == NULL)654+ return false;655+ setCoinsRet.insert(coinLowestLarger.second);656+ nValueRet += coinLowestLarger.first;657+ return true;658+ }659+660+ if (nTotalLower >= nTargetValue + CENT)661+ nTargetValue += CENT;662+663+ // Solve subset sum by stochastic approximation664+ sort(vValue.rbegin(), vValue.rend());665+ vector<char> vfIncluded;666+ vector<char> vfBest(vValue.size(), true);667+ int64 nBest = nTotalLower;668+669+ for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)670+ {671+ vfIncluded.assign(vValue.size(), false);672+ int64 nTotal = 0;673+ bool fReachedTarget = false;674+ for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)675+ {676+ for (int i = 0; i < vValue.size(); i++)677+ {678+ if (nPass == 0 ? rand() % 2 : !vfIncluded[i])679+ {680+ nTotal += vValue[i].first;681+ vfIncluded[i] = true;682+ if (nTotal >= nTargetValue)683+ {684+ fReachedTarget = true;685+ if (nTotal < nBest)686+ {687+ nBest = nTotal;688+ vfBest = vfIncluded;689+ }690+ nTotal -= vValue[i].first;691+ vfIncluded[i] = false;692+ }693+ }694+ }695+ }696+ }697+698+ // If the next larger is still closer, return it699+ if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)700+ {701+ setCoinsRet.insert(coinLowestLarger.second);702+ nValueRet += coinLowestLarger.first;703+ }704+ else {705+ for (int i = 0; i < vValue.size(); i++)706+ if (vfBest[i])707+ {708+ setCoinsRet.insert(vValue[i].second);709+ nValueRet += vValue[i].first;710+ }711+712+ //// debug print713+ printf("SelectCoins() best subset: ");714+ for (int i = 0; i < vValue.size(); i++)715+ if (vfBest[i])716+ printf("%s ", FormatMoney(vValue[i].first).c_str());717+ printf("total %s\n", FormatMoney(nBest).c_str());718+ }719+720+ return true;721+}722+723+bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const724+{725+ return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||726+ SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||727+ SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));728+}729+730+731+732+733+bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)734+{735+ int64 nValue = 0;736+ BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)737+ {738+ if (nValue < 0)739+ return false;740+ nValue += s.second;741+ }742+ if (vecSend.empty() || nValue < 0)743+ return false;744+745+ wtxNew.pwallet = this;746+747+ CRITICAL_BLOCK(cs_main)748+ {749+ // txdb must be opened before the mapWallet lock750+ CTxDB txdb("r");751+ CRITICAL_BLOCK(cs_mapWallet)752+ {753+ nFeeRet = nTransactionFee;754+ loop755+ {756+ wtxNew.vin.clear();757+ wtxNew.vout.clear();758+ wtxNew.fFromMe = true;759+760+ int64 nTotalValue = nValue + nFeeRet;761+ double dPriority = 0;762+ // vouts to the payees763+ BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)764+ wtxNew.vout.push_back(CTxOut(s.second, s.first));765+766+ // Choose coins to use767+ set<pair<const CWalletTx*,unsigned int> > setCoins;768+ int64 nValueIn = 0;769+ if (!SelectCoins(nTotalValue, setCoins, nValueIn))770+ return false;771+ BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)772+ {773+ int64 nCredit = pcoin.first->vout[pcoin.second].nValue;774+ dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();775+ }776+777+ // Fill a vout back to self with any change778+ int64 nChange = nValueIn - nTotalValue;779+ if (nChange >= CENT)780+ {781+ // Note: We use a new key here to keep it from being obvious which side is the change.782+ // The drawback is that by not reusing a previous key, the change may be lost if a783+ // backup is restored, if the backup doesn't have the new private key for the change.784+ // If we reused the old key, it would be possible to add code to look for and785+ // rediscover unknown transactions that were written with keys of ours to recover786+ // post-backup change.787+788+ // Reserve a new key pair from key pool789+ vector<unsigned char> vchPubKey = reservekey.GetReservedKey();790+ assert(mapKeys.count(vchPubKey));791+792+ // Fill a vout to ourself, using same address type as the payment793+ CScript scriptChange;794+ if (vecSend[0].first.GetBitcoinAddressHash160() != 0)795+ scriptChange.SetBitcoinAddress(vchPubKey);796+ else797+ scriptChange << vchPubKey << OP_CHECKSIG;798+799+ // Insert change txn at random position:800+ vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());801+ wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));802+ }803+ else804+ reservekey.ReturnKey();805+806+ // Fill vin807+ BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)808+ wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));809+810+ // Sign811+ int nIn = 0;812+ BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)813+ if (!SignSignature(*this, *coin.first, wtxNew, nIn++))814+ return false;815+816+ // Limit size817+ unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);818+ if (nBytes >= MAX_BLOCK_SIZE_GEN/5)819+ return false;820+ dPriority /= nBytes;821+822+ // Check that enough fee is included823+ int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);824+ bool fAllowFree = CTransaction::AllowFree(dPriority);825+ int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);826+ if (nFeeRet < max(nPayFee, nMinFee))827+ {828+ nFeeRet = max(nPayFee, nMinFee);829+ continue;830+ }831+832+ // Fill vtxPrev by copying from previous transactions vtxPrev833+ wtxNew.AddSupportingTransactions(txdb);834+ wtxNew.fTimeReceivedIsTxTime = true;835+836+ break;837+ }838+ }839+ }840+ return true;841+}842+843+bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)844+{845+ vector< pair<CScript, int64> > vecSend;846+ vecSend.push_back(make_pair(scriptPubKey, nValue));847+ return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);848+}849+850+// Call after CreateTransaction unless you want to abort851+bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)852+{853+ CRITICAL_BLOCK(cs_main)854+ {855+ printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());856+ CRITICAL_BLOCK(cs_mapWallet)857+ {858+ // This is only to keep the database open to defeat the auto-flush for the859+ // duration of this scope. This is the only place where this optimization860+ // maybe makes sense; please don't do it anywhere else.861+ CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;862+863+ // Take key pair from key pool so it won't be used again864+ reservekey.KeepKey();865+866+ // Add tx to wallet, because if it has change it's also ours,867+ // otherwise just for transaction history.868+ AddToWallet(wtxNew);869+870+ // Mark old coins as spent871+ set<CWalletTx*> setCoins;872+ BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)873+ {874+ CWalletTx &coin = mapWallet[txin.prevout.hash];875+ coin.pwallet = this;876+ coin.MarkSpent(txin.prevout.n);877+ coin.WriteToDisk();878+ vWalletUpdated.push_back(coin.GetHash());879+ }880+881+ if (fFileBacked)882+ delete pwalletdb;883+ }884+885+ // Track how many getdata requests our transaction gets886+ CRITICAL_BLOCK(cs_mapRequestCount)887+ mapRequestCount[wtxNew.GetHash()] = 0;888+889+ // Broadcast890+ if (!wtxNew.AcceptToMemoryPool())891+ {892+ // This must not fail. The transaction has already been signed and recorded.893+ printf("CommitTransaction() : Error: Transaction not valid");894+ return false;895+ }896+ wtxNew.RelayWalletTransaction();897+ }898+ MainFrameRepaint();899+ return true;900+}901+902+903+904+905+// requires cs_main lock906+string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)907+{908+ CReserveKey reservekey(this);909+ int64 nFeeRequired;910+ if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))911+ {912+ string strError;913+ if (nValue + nFeeRequired > GetBalance())914+ 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());915+ else916+ strError = _("Error: Transaction creation failed ");917+ printf("SendMoney() : %s", strError.c_str());918+ return strError;919+ }920+921+ if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))922+ return "ABORTED";923+924+ if (!CommitTransaction(wtxNew, reservekey))925+ 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.");926+927+ MainFrameRepaint();928+ return "";929+}930+931+932+933+// requires cs_main lock934+string CWallet::SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)935+{936+ // Check amount937+ if (nValue <= 0)938+ return _("Invalid amount");939+ if (nValue + nTransactionFee > GetBalance())940+ return _("Insufficient funds");941+942+ // Parse bitcoin address943+ CScript scriptPubKey;944+ if (!scriptPubKey.SetBitcoinAddress(strAddress))945+ return _("Invalid bitcoin address");946+947+ return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);948+}949+950+951+952+953+bool CWallet::LoadWallet(bool& fFirstRunRet)954+{955+ if (!fFileBacked)956+ return false;957+ fFirstRunRet = false;958+ if (!CWalletDB(strWalletFile,"cr+").LoadWallet(this))959+ return false;960+ fFirstRunRet = vchDefaultKey.empty();961+962+ if (!mapKeys.count(vchDefaultKey))963+ {964+ // Create new default key965+ RandAddSeedPerfmon();966+967+ SetDefaultKey(GetKeyFromKeyPool());968+ if (!SetAddressBookName(PubKeyToAddress(vchDefaultKey), ""))969+ return false;970+ }971+972+ CreateThread(ThreadFlushWalletDB, &strWalletFile);973+ return true;974+}975+976+977+bool CWallet::SetAddressBookName(const string& strAddress, const string& strName)978+{979+ mapAddressBook[strAddress] = strName;980+ if (!fFileBacked)981+ return false;982+ return CWalletDB(strWalletFile).WriteName(strAddress, strName);983+}984+985+bool CWallet::DelAddressBookName(const string& strAddress)986+{987+ mapAddressBook.erase(strAddress);988+ if (!fFileBacked)989+ return false;990+ return CWalletDB(strWalletFile).EraseName(strAddress);991+}992+993+994+void CWallet::PrintWallet(const CBlock& block)995+{996+ CRITICAL_BLOCK(cs_mapWallet)997+ {998+ if (mapWallet.count(block.vtx[0].GetHash()))999+ {1000+ CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];1001+ printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());1002+ }1003+ }1004+ printf("\n");1005+}1006+1007+bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)1008+{1009+ CRITICAL_BLOCK(cs_mapWallet)1010+ {1011+ map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);1012+ if (mi != mapWallet.end())1013+ {1014+ wtx = (*mi).second;1015+ return true;1016+ }1017+ }1018+ return false;1019+}1020+1021+bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey)1022+{1023+ if (fFileBacked)1024+ {1025+ if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))1026+ return false;1027+ }1028+ vchDefaultKey = vchPubKey;1029+ return true;1030+}1031+1032+bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)1033+{1034+ if (!pwallet->fFileBacked)1035+ return false;1036+ strWalletFileOut = pwallet->strWalletFile;1037+ return true;1038+}1039+1040+void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)1041+{1042+ nIndex = -1;1043+ keypool.vchPubKey.clear();1044+ CRITICAL_BLOCK(cs_main)1045+ CRITICAL_BLOCK(cs_mapWallet)1046+ CRITICAL_BLOCK(cs_setKeyPool)1047+ {1048+ CWalletDB walletdb(strWalletFile);1049+1050+ // Top up key pool1051+ int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);1052+ while (setKeyPool.size() < nTargetSize+1)1053+ {1054+ int64 nEnd = 1;1055+ if (!setKeyPool.empty())1056+ nEnd = *(--setKeyPool.end()) + 1;1057+ if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))1058+ throw runtime_error("ReserveKeyFromKeyPool() : writing generated key failed");1059+ setKeyPool.insert(nEnd);1060+ printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());1061+ }1062+1063+ // Get the oldest key1064+ assert(!setKeyPool.empty());1065+ nIndex = *(setKeyPool.begin());1066+ setKeyPool.erase(setKeyPool.begin());1067+ if (!walletdb.ReadPool(nIndex, keypool))1068+ throw runtime_error("ReserveKeyFromKeyPool() : read failed");1069+ if (!mapKeys.count(keypool.vchPubKey))1070+ throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");1071+ assert(!keypool.vchPubKey.empty());1072+ printf("keypool reserve %"PRI64d"\n", nIndex);1073+ }1074+}1075+1076+void CWallet::KeepKey(int64 nIndex)1077+{1078+ // Remove from key pool1079+ if (fFileBacked)1080+ {1081+ CWalletDB walletdb(strWalletFile);1082+ CRITICAL_BLOCK(cs_main)1083+ {1084+ walletdb.ErasePool(nIndex);1085+ }1086+ }1087+ printf("keypool keep %"PRI64d"\n", nIndex);1088+}1089+1090+void CWallet::ReturnKey(int64 nIndex)1091+{1092+ // Return to key pool1093+ CRITICAL_BLOCK(cs_setKeyPool)1094+ setKeyPool.insert(nIndex);1095+ printf("keypool return %"PRI64d"\n", nIndex);1096+}1097+1098+vector<unsigned char> CWallet::GetKeyFromKeyPool()1099+{1100+ int64 nIndex = 0;1101+ CKeyPool keypool;1102+ ReserveKeyFromKeyPool(nIndex, keypool);1103+ KeepKey(nIndex);1104+ return keypool.vchPubKey;1105+}1106+1107+int64 CWallet::GetOldestKeyPoolTime()1108+{1109+ int64 nIndex = 0;1110+ CKeyPool keypool;1111+ ReserveKeyFromKeyPool(nIndex, keypool);1112+ ReturnKey(nIndex);1113+ return keypool.nTime;1114+}1115+1116+vector<unsigned char> CReserveKey::GetReservedKey()1117+{1118+ if (nIndex == -1)1119+ {1120+ CKeyPool keypool;1121+ pwallet->ReserveKeyFromKeyPool(nIndex, keypool);1122+ vchPubKey = keypool.vchPubKey;1123+ }1124+ assert(!vchPubKey.empty());1125+ return vchPubKey;1126+}1127+1128+void CReserveKey::KeepKey()1129+{1130+ if (nIndex != -1)1131+ pwallet->KeepKey(nIndex);1132+ nIndex = -1;1133+ vchPubKey.clear();1134+}1135+1136+void CReserveKey::ReturnKey()1137+{1138+ if (nIndex != -1)1139+ pwallet->ReturnKey(nIndex);1140+ nIndex = -1;1141+ vchPubKey.clear();1142+}1143+1144+
wallet.h (added)
1--- /dev/null2+++ v0.3.24/wallet.h3@@ -1 +1,615 @@4-5+// Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers6+// Distributed under the MIT/X11 software license, see the accompanying7+// file license.txt or http://www.opensource.org/licenses/mit-license.php.8+#ifndef BITCOIN_WALLET_H9+#define BITCOIN_WALLET_H10+11+#include "bignum.h"12+#include "key.h"13+#include "script.h"14+15+class CWalletTx;16+class CReserveKey;17+class CWalletDB;18+19+class CWallet : public CKeyStore20+{21+private:22+ bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;23+ bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;24+25+26+public:27+ bool fFileBacked;28+ std::string strWalletFile;29+30+ std::set<int64> setKeyPool;31+ CCriticalSection cs_setKeyPool;32+33+ CWallet()34+ {35+ fFileBacked = false;36+ }37+ CWallet(std::string strWalletFileIn)38+ {39+ strWalletFile = strWalletFileIn;40+ fFileBacked = true;41+ }42+43+ mutable CCriticalSection cs_mapWallet;44+ std::map<uint256, CWalletTx> mapWallet;45+ std::vector<uint256> vWalletUpdated;46+47+ std::map<uint256, int> mapRequestCount;48+ mutable CCriticalSection cs_mapRequestCount;49+50+ std::map<std::string, std::string> mapAddressBook;51+ mutable CCriticalSection cs_mapAddressBook;52+53+ std::vector<unsigned char> vchDefaultKey;54+55+ bool AddKey(const CKey& key);56+ bool AddToWallet(const CWalletTx& wtxIn);57+ bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);58+ bool EraseFromWallet(uint256 hash);59+ void WalletUpdateSpent(const CTransaction& prevout);60+ int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);61+ void ReacceptWalletTransactions();62+ void ResendWalletTransactions();63+ int64 GetBalance() const;64+ bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);65+ bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);66+ bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);67+ bool BroadcastTransaction(CWalletTx& wtxNew);68+ std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);69+ std::string SendMoneyToBitcoinAddress(std::string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);70+71+ void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);72+ void KeepKey(int64 nIndex);73+ void ReturnKey(int64 nIndex);74+ std::vector<unsigned char> GetKeyFromKeyPool();75+ int64 GetOldestKeyPoolTime();76+77+ bool IsMine(const CTxIn& txin) const;78+ int64 GetDebit(const CTxIn& txin) const;79+ bool IsMine(const CTxOut& txout) const80+ {81+ return ::IsMine(*this, txout.scriptPubKey);82+ }83+ int64 GetCredit(const CTxOut& txout) const84+ {85+ if (!MoneyRange(txout.nValue))86+ throw std::runtime_error("CWallet::GetCredit() : value out of range");87+ return (IsMine(txout) ? txout.nValue : 0);88+ }89+ bool IsChange(const CTxOut& txout) const90+ {91+ std::vector<unsigned char> vchPubKey;92+ if (ExtractPubKey(txout.scriptPubKey, this, vchPubKey))93+ CRITICAL_BLOCK(cs_mapAddressBook)94+ if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))95+ return true;96+ return false;97+ }98+ int64 GetChange(const CTxOut& txout) const99+ {100+ if (!MoneyRange(txout.nValue))101+ throw std::runtime_error("CWallet::GetChange() : value out of range");102+ return (IsChange(txout) ? txout.nValue : 0);103+ }104+ bool IsMine(const CTransaction& tx) const105+ {106+ BOOST_FOREACH(const CTxOut& txout, tx.vout)107+ if (IsMine(txout))108+ return true;109+ return false;110+ }111+ bool IsFromMe(const CTransaction& tx) const112+ {113+ return (GetDebit(tx) > 0);114+ }115+ int64 GetDebit(const CTransaction& tx) const116+ {117+ int64 nDebit = 0;118+ BOOST_FOREACH(const CTxIn& txin, tx.vin)119+ {120+ nDebit += GetDebit(txin);121+ if (!MoneyRange(nDebit))122+ throw std::runtime_error("CWallet::GetDebit() : value out of range");123+ }124+ return nDebit;125+ }126+ int64 GetCredit(const CTransaction& tx) const127+ {128+ int64 nCredit = 0;129+ BOOST_FOREACH(const CTxOut& txout, tx.vout)130+ {131+ nCredit += GetCredit(txout);132+ if (!MoneyRange(nCredit))133+ throw std::runtime_error("CWallet::GetCredit() : value out of range");134+ }135+ return nCredit;136+ }137+ int64 GetChange(const CTransaction& tx) const138+ {139+ int64 nChange = 0;140+ BOOST_FOREACH(const CTxOut& txout, tx.vout)141+ {142+ nChange += GetChange(txout);143+ if (!MoneyRange(nChange))144+ throw std::runtime_error("CWallet::GetChange() : value out of range");145+ }146+ return nChange;147+ }148+ void SetBestChain(const CBlockLocator& loc)149+ {150+ CWalletDB walletdb(strWalletFile);151+ walletdb.WriteBestBlock(loc);152+ }153+154+ bool LoadWallet(bool& fFirstRunRet);155+// bool BackupWallet(const std::string& strDest);156+157+ // requires cs_mapAddressBook lock158+ bool SetAddressBookName(const std::string& strAddress, const std::string& strName);159+160+ // requires cs_mapAddressBook lock161+ bool DelAddressBookName(const std::string& strAddress);162+163+ void UpdatedTransaction(const uint256 &hashTx)164+ {165+ CRITICAL_BLOCK(cs_mapWallet)166+ vWalletUpdated.push_back(hashTx);167+ }168+169+ void PrintWallet(const CBlock& block);170+171+ void Inventory(const uint256 &hash)172+ {173+ CRITICAL_BLOCK(cs_mapRequestCount)174+ {175+ std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);176+ if (mi != mapRequestCount.end())177+ (*mi).second++;178+ }179+ }180+181+ bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);182+183+ bool SetDefaultKey(const std::vector<unsigned char> &vchPubKey);184+};185+186+187+class CReserveKey188+{189+protected:190+ CWallet* pwallet;191+ int64 nIndex;192+ std::vector<unsigned char> vchPubKey;193+public:194+ CReserveKey(CWallet* pwalletIn)195+ {196+ nIndex = -1;197+ pwallet = pwalletIn;198+ }199+200+ ~CReserveKey()201+ {202+ if (!fShutdown)203+ ReturnKey();204+ }205+206+ void ReturnKey();207+ std::vector<unsigned char> GetReservedKey();208+ void KeepKey();209+};210+211+212+//213+// A transaction with a bunch of additional info that only the owner cares214+// about. It includes any unrecorded transactions needed to link it back215+// to the block chain.216+//217+class CWalletTx : public CMerkleTx218+{219+public:220+ const CWallet* pwallet;221+222+ std::vector<CMerkleTx> vtxPrev;223+ std::map<std::string, std::string> mapValue;224+ std::vector<std::pair<std::string, std::string> > vOrderForm;225+ unsigned int fTimeReceivedIsTxTime;226+ unsigned int nTimeReceived; // time received by this node227+ char fFromMe;228+ std::string strFromAccount;229+ std::vector<char> vfSpent;230+231+ // memory only232+ mutable char fDebitCached;233+ mutable char fCreditCached;234+ mutable char fAvailableCreditCached;235+ mutable char fChangeCached;236+ mutable int64 nDebitCached;237+ mutable int64 nCreditCached;238+ mutable int64 nAvailableCreditCached;239+ mutable int64 nChangeCached;240+241+ // memory only UI hints242+ mutable unsigned int nTimeDisplayed;243+ mutable int nLinesDisplayed;244+ mutable char fConfirmedDisplayed;245+246+ CWalletTx()247+ {248+ Init(NULL);249+ }250+251+ CWalletTx(const CWallet* pwalletIn)252+ {253+ Init(pwalletIn);254+ }255+256+ CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)257+ {258+ Init(pwalletIn);259+ }260+261+ CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)262+ {263+ Init(pwalletIn);264+ }265+266+ void Init(const CWallet* pwalletIn)267+ {268+ pwallet = pwalletIn;269+ vtxPrev.clear();270+ mapValue.clear();271+ vOrderForm.clear();272+ fTimeReceivedIsTxTime = false;273+ nTimeReceived = 0;274+ fFromMe = false;275+ strFromAccount.clear();276+ vfSpent.clear();277+ fDebitCached = false;278+ fCreditCached = false;279+ fAvailableCreditCached = false;280+ fChangeCached = false;281+ nDebitCached = 0;282+ nCreditCached = 0;283+ nAvailableCreditCached = 0;284+ nChangeCached = 0;285+ nTimeDisplayed = 0;286+ nLinesDisplayed = 0;287+ fConfirmedDisplayed = false;288+ }289+290+ IMPLEMENT_SERIALIZE291+ (292+ CWalletTx* pthis = const_cast<CWalletTx*>(this);293+ if (fRead)294+ pthis->Init(NULL);295+ char fSpent = false;296+297+ if (!fRead)298+ {299+ pthis->mapValue["fromaccount"] = pthis->strFromAccount;300+301+ std::string str;302+ BOOST_FOREACH(char f, vfSpent)303+ {304+ str += (f ? '1' : '0');305+ if (f)306+ fSpent = true;307+ }308+ pthis->mapValue["spent"] = str;309+ }310+311+ nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);312+ READWRITE(vtxPrev);313+ READWRITE(mapValue);314+ READWRITE(vOrderForm);315+ READWRITE(fTimeReceivedIsTxTime);316+ READWRITE(nTimeReceived);317+ READWRITE(fFromMe);318+ READWRITE(fSpent);319+320+ if (fRead)321+ {322+ pthis->strFromAccount = pthis->mapValue["fromaccount"];323+324+ if (mapValue.count("spent"))325+ BOOST_FOREACH(char c, pthis->mapValue["spent"])326+ pthis->vfSpent.push_back(c != '0');327+ else328+ pthis->vfSpent.assign(vout.size(), fSpent);329+ }330+331+ pthis->mapValue.erase("fromaccount");332+ pthis->mapValue.erase("version");333+ pthis->mapValue.erase("spent");334+ )335+336+ // marks certain txout's as spent337+ // returns true if any update took place338+ bool UpdateSpent(const std::vector<char>& vfNewSpent)339+ {340+ bool fReturn = false;341+ for (int i=0; i < vfNewSpent.size(); i++)342+ {343+ if (i == vfSpent.size())344+ break;345+346+ if (vfNewSpent[i] && !vfSpent[i])347+ {348+ vfSpent[i] = true;349+ fReturn = true;350+ fAvailableCreditCached = false;351+ }352+ }353+ return fReturn;354+ }355+356+ void MarkDirty()357+ {358+ fCreditCached = false;359+ fAvailableCreditCached = false;360+ fDebitCached = false;361+ fChangeCached = false;362+ }363+364+ void MarkSpent(unsigned int nOut)365+ {366+ if (nOut >= vout.size())367+ throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");368+ vfSpent.resize(vout.size());369+ if (!vfSpent[nOut])370+ {371+ vfSpent[nOut] = true;372+ fAvailableCreditCached = false;373+ }374+ }375+376+ bool IsSpent(unsigned int nOut) const377+ {378+ if (nOut >= vout.size())379+ throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");380+ if (nOut >= vfSpent.size())381+ return false;382+ return (!!vfSpent[nOut]);383+ }384+385+ int64 GetDebit() const386+ {387+ if (vin.empty())388+ return 0;389+ if (fDebitCached)390+ return nDebitCached;391+ nDebitCached = pwallet->GetDebit(*this);392+ fDebitCached = true;393+ return nDebitCached;394+ }395+396+ int64 GetCredit(bool fUseCache=true) const397+ {398+ // Must wait until coinbase is safely deep enough in the chain before valuing it399+ if (IsCoinBase() && GetBlocksToMaturity() > 0)400+ return 0;401+402+ // GetBalance can assume transactions in mapWallet won't change403+ if (fUseCache && fCreditCached)404+ return nCreditCached;405+ nCreditCached = pwallet->GetCredit(*this);406+ fCreditCached = true;407+ return nCreditCached;408+ }409+410+ int64 GetAvailableCredit(bool fUseCache=true) const411+ {412+ // Must wait until coinbase is safely deep enough in the chain before valuing it413+ if (IsCoinBase() && GetBlocksToMaturity() > 0)414+ return 0;415+416+ if (fUseCache && fAvailableCreditCached)417+ return nAvailableCreditCached;418+419+ int64 nCredit = 0;420+ for (int i = 0; i < vout.size(); i++)421+ {422+ if (!IsSpent(i))423+ {424+ const CTxOut &txout = vout[i];425+ nCredit += pwallet->GetCredit(txout);426+ if (!MoneyRange(nCredit))427+ throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");428+ }429+ }430+431+ nAvailableCreditCached = nCredit;432+ fAvailableCreditCached = true;433+ return nCredit;434+ }435+436+437+ int64 GetChange() const438+ {439+ if (fChangeCached)440+ return nChangeCached;441+ nChangeCached = pwallet->GetChange(*this);442+ fChangeCached = true;443+ return nChangeCached;444+ }445+446+ void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,447+ std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;448+449+ void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived, 450+ int64& nSent, int64& nFee) const;451+452+ bool IsFromMe() const453+ {454+ return (GetDebit() > 0);455+ }456+457+ bool IsConfirmed() const458+ {459+ // Quick answer in most cases460+ if (!IsFinal())461+ return false;462+ if (GetDepthInMainChain() >= 1)463+ return true;464+ if (!IsFromMe()) // using wtx's cached debit465+ return false;466+467+ // If no confirmations but it's from us, we can still468+ // consider it confirmed if all dependencies are confirmed469+ std::map<uint256, const CMerkleTx*> mapPrev;470+ std::vector<const CMerkleTx*> vWorkQueue;471+ vWorkQueue.reserve(vtxPrev.size()+1);472+ vWorkQueue.push_back(this);473+ for (int i = 0; i < vWorkQueue.size(); i++)474+ {475+ const CMerkleTx* ptx = vWorkQueue[i];476+477+ if (!ptx->IsFinal())478+ return false;479+ if (ptx->GetDepthInMainChain() >= 1)480+ continue;481+ if (!pwallet->IsFromMe(*ptx))482+ return false;483+484+ if (mapPrev.empty())485+ BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)486+ mapPrev[tx.GetHash()] = &tx;487+488+ BOOST_FOREACH(const CTxIn& txin, ptx->vin)489+ {490+ if (!mapPrev.count(txin.prevout.hash))491+ return false;492+ vWorkQueue.push_back(mapPrev[txin.prevout.hash]);493+ }494+ }495+ return true;496+ }497+498+ bool WriteToDisk();499+500+ int64 GetTxTime() const;501+ int GetRequestCount() const;502+503+ void AddSupportingTransactions(CTxDB& txdb);504+505+ bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);506+ bool AcceptWalletTransaction();507+508+ void RelayWalletTransaction(CTxDB& txdb);509+ void RelayWalletTransaction();510+};511+512+513+//514+// Private key that includes an expiration date in case it never gets used.515+//516+class CWalletKey517+{518+public:519+ CPrivKey vchPrivKey;520+ int64 nTimeCreated;521+ int64 nTimeExpires;522+ std::string strComment;523+ //// todo: add something to note what created it (user, getnewaddress, change)524+ //// maybe should have a map<string, string> property map525+526+ CWalletKey(int64 nExpires=0)527+ {528+ nTimeCreated = (nExpires ? GetTime() : 0);529+ nTimeExpires = nExpires;530+ }531+532+ IMPLEMENT_SERIALIZE533+ (534+ if (!(nType & SER_GETHASH))535+ READWRITE(nVersion);536+ READWRITE(vchPrivKey);537+ READWRITE(nTimeCreated);538+ READWRITE(nTimeExpires);539+ READWRITE(strComment);540+ )541+};542+543+544+545+546+547+548+//549+// Account information.550+// Stored in wallet with key "acc"+string account name551+//552+class CAccount553+{554+public:555+ std::vector<unsigned char> vchPubKey;556+557+ CAccount()558+ {559+ SetNull();560+ }561+562+ void SetNull()563+ {564+ vchPubKey.clear();565+ }566+567+ IMPLEMENT_SERIALIZE568+ (569+ if (!(nType & SER_GETHASH))570+ READWRITE(nVersion);571+ READWRITE(vchPubKey);572+ )573+};574+575+576+577+//578+// Internal transfers.579+// Database key is acentry<account><counter>580+//581+class CAccountingEntry582+{583+public:584+ std::string strAccount;585+ int64 nCreditDebit;586+ int64 nTime;587+ std::string strOtherAccount;588+ std::string strComment;589+590+ CAccountingEntry()591+ {592+ SetNull();593+ }594+595+ void SetNull()596+ {597+ nCreditDebit = 0;598+ nTime = 0;599+ strAccount.clear();600+ strOtherAccount.clear();601+ strComment.clear();602+ }603+604+ IMPLEMENT_SERIALIZE605+ (606+ if (!(nType & SER_GETHASH))607+ READWRITE(nVersion);608+ // Note: strAccount is serialized as part of the key, not here.609+ READWRITE(nCreditDebit);610+ READWRITE(nTime);611+ READWRITE(strOtherAccount);612+ READWRITE(strComment);613+ )614+};615+616+bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);617+618+#endif619+
