Browse Source

Merge pull request #288 from sipa/walletclass

CWallet class
0.8
Pieter Wuille 14 years ago
parent
commit
a6b2115963
  1. 166
      src/db.cpp
  2. 118
      src/db.h
  3. 2
      src/headers.h
  4. 22
      src/init.cpp
  5. 2
      src/init.h
  6. 33
      src/keystore.cpp
  7. 26
      src/keystore.h
  8. 1441
      src/main.cpp
  9. 567
      src/main.h
  10. 4
      src/makefile.mingw
  11. 4
      src/makefile.osx
  12. 4
      src/makefile.unix
  13. 4
      src/net.cpp
  14. 2
      src/noui.h
  15. 148
      src/rpc.cpp
  16. 31
      src/script.cpp
  17. 8
      src/script.h
  18. 187
      src/ui.cpp
  19. 3
      src/ui.h
  20. 1123
      src/wallet.cpp
  21. 615
      src/wallet.h

166
src/db.cpp

@ -10,8 +10,6 @@ @@ -10,8 +10,6 @@
using namespace std;
using namespace boost;
void ThreadFlushWalletDB(void* parg);
unsigned int nWalletDBUpdated;
uint64 nAccountingEntryNumber = 0;
@ -150,7 +148,7 @@ void CDB::Close() @@ -150,7 +148,7 @@ void CDB::Close()
--mapFileUseCount[strFile];
}
void CloseDb(const string& strFile)
void static CloseDb(const string& strFile)
{
CRITICAL_BLOCK(cs_db)
{
@ -359,7 +357,7 @@ bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork) @@ -359,7 +357,7 @@ bool CTxDB::WriteBestInvalidWork(CBigNum bnBestInvalidWork)
return Write(string("bnBestInvalidWork"), bnBestInvalidWork);
}
CBlockIndex* InsertBlockIndex(uint256 hash)
CBlockIndex static * InsertBlockIndex(uint256 hash)
{
if (hash == 0)
return NULL;
@ -584,8 +582,19 @@ bool LoadAddresses() @@ -584,8 +582,19 @@ bool LoadAddresses()
// CWalletDB
//
static set<int64> setKeyPool;
static CCriticalSection cs_setKeyPool;
bool CWalletDB::WriteName(const string& strAddress, const string& strName)
{
nWalletDBUpdated++;
return Write(make_pair(string("name"), strAddress), strName);
}
bool CWalletDB::EraseName(const string& strAddress)
{
// This should only be used for sending addresses, never for receiving addresses,
// receiving addresses must always have an address book entry if they're not change return.
nWalletDBUpdated++;
return Erase(make_pair(string("name"), strAddress));
}
bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
{
@ -660,9 +669,9 @@ void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountin @@ -660,9 +669,9 @@ void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountin
}
bool CWalletDB::LoadWallet()
bool CWalletDB::LoadWallet(CWallet* pwallet)
{
vchDefaultKey.clear();
pwallet->vchDefaultKey.clear();
int nFileVersion = 0;
vector<uint256> vWalletUpgrade;
@ -674,8 +683,8 @@ bool CWalletDB::LoadWallet() @@ -674,8 +683,8 @@ bool CWalletDB::LoadWallet()
#endif
//// todo: shouldn't we catch exceptions and try to recover and continue?
CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(cs_mapKeys)
CRITICAL_BLOCK(pwallet->cs_mapWallet)
CRITICAL_BLOCK(pwallet->cs_mapKeys)
{
// Get cursor
Dbc* pcursor = GetCursor();
@ -702,14 +711,15 @@ bool CWalletDB::LoadWallet() @@ -702,14 +711,15 @@ bool CWalletDB::LoadWallet()
{
string strAddress;
ssKey >> strAddress;
ssValue >> mapAddressBook[strAddress];
ssValue >> pwallet->mapAddressBook[strAddress];
}
else if (strType == "tx")
{
uint256 hash;
ssKey >> hash;
CWalletTx& wtx = mapWallet[hash];
CWalletTx& wtx = pwallet->mapWallet[hash];
ssValue >> wtx;
wtx.pwallet = pwallet;
if (wtx.GetHash() != hash)
printf("Error in wallet.dat, hash mismatch\n");
@ -760,18 +770,18 @@ bool CWalletDB::LoadWallet() @@ -760,18 +770,18 @@ bool CWalletDB::LoadWallet()
else
ssValue >> wkey;
mapKeys[vchPubKey] = wkey.vchPrivKey;
pwallet->mapKeys[vchPubKey] = wkey.vchPrivKey;
mapPubKeys[Hash160(vchPubKey)] = vchPubKey;
}
else if (strType == "defaultkey")
{
ssValue >> vchDefaultKey;
ssValue >> pwallet->vchDefaultKey;
}
else if (strType == "pool")
{
int64 nIndex;
ssKey >> nIndex;
setKeyPool.insert(nIndex);
pwallet->setKeyPool.insert(nIndex);
}
else if (strType == "version")
{
@ -803,7 +813,7 @@ bool CWalletDB::LoadWallet() @@ -803,7 +813,7 @@ bool CWalletDB::LoadWallet()
}
BOOST_FOREACH(uint256 hash, vWalletUpgrade)
WriteTx(hash, mapWallet[hash]);
WriteTx(hash, pwallet->mapWallet[hash]);
printf("nFileVersion = %d\n", nFileVersion);
printf("fGenerateBitcoins = %d\n", fGenerateBitcoins);
@ -831,36 +841,9 @@ bool CWalletDB::LoadWallet() @@ -831,36 +841,9 @@ bool CWalletDB::LoadWallet()
return true;
}
bool LoadWallet(bool& fFirstRunRet)
{
fFirstRunRet = false;
if (!CWalletDB("cr+").LoadWallet())
return false;
fFirstRunRet = vchDefaultKey.empty();
if (mapKeys.count(vchDefaultKey))
{
// Set keyUser
keyUser.SetPubKey(vchDefaultKey);
keyUser.SetPrivKey(mapKeys[vchDefaultKey]);
}
else
{
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CWalletDB walletdb;
vchDefaultKey = GetKeyFromKeyPool();
walletdb.WriteDefaultKey(vchDefaultKey);
walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
}
CreateThread(ThreadFlushWalletDB, NULL);
return true;
}
void ThreadFlushWalletDB(void* parg)
{
const string& strFile = ((const string*)parg)[0];
static bool fOneThread;
if (fOneThread)
return;
@ -896,7 +879,6 @@ void ThreadFlushWalletDB(void* parg) @@ -896,7 +879,6 @@ void ThreadFlushWalletDB(void* parg)
if (nRefCount == 0 && !fShutdown)
{
string strFile = "wallet.dat";
map<string, int>::iterator mi = mapFileUseCount.find(strFile);
if (mi != mapFileUseCount.end())
{
@ -919,26 +901,27 @@ void ThreadFlushWalletDB(void* parg) @@ -919,26 +901,27 @@ void ThreadFlushWalletDB(void* parg)
}
}
void BackupWallet(const string& strDest)
bool BackupWallet(const CWallet& wallet, const string& strDest)
{
if (!wallet.fFileBacked)
return false;
while (!fShutdown)
{
CRITICAL_BLOCK(cs_db)
{
const string strFile = "wallet.dat";
if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0)
{
// Flush log data to the dat file
CloseDb(strFile);
CloseDb(wallet.strWalletFile);
dbenv.txn_checkpoint(0, 0, 0);
dbenv.lsn_reset(strFile.c_str(), 0);
mapFileUseCount.erase(strFile);
dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0);
mapFileUseCount.erase(wallet.strWalletFile);
// Copy wallet.dat
filesystem::path pathSrc(GetDataDir() + "/" + strFile);
filesystem::path pathSrc(GetDataDir() + "/" + wallet.strWalletFile);
filesystem::path pathDest(strDest);
if (filesystem::is_directory(pathDest))
pathDest = pathDest / strFile;
pathDest = pathDest / wallet.strWalletFile;
#if BOOST_VERSION >= 104000
filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
#else
@ -946,83 +929,10 @@ void BackupWallet(const string& strDest) @@ -946,83 +929,10 @@ void BackupWallet(const string& strDest)
#endif
printf("copied wallet.dat to %s\n", pathDest.string().c_str());
return;
return true;
}
}
Sleep(100);
}
}
void CWalletDB::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
{
nIndex = -1;
keypool.vchPubKey.clear();
CRITICAL_BLOCK(cs_main)
CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(cs_setKeyPool)
{
// Top up key pool
int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
while (setKeyPool.size() < nTargetSize+1)
{
int64 nEnd = 1;
if (!setKeyPool.empty())
nEnd = *(--setKeyPool.end()) + 1;
if (!Write(make_pair(string("pool"), nEnd), CKeyPool(GenerateNewKey())))
throw runtime_error("ReserveKeyFromKeyPool() : writing generated key failed");
setKeyPool.insert(nEnd);
printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
}
// Get the oldest key
assert(!setKeyPool.empty());
nIndex = *(setKeyPool.begin());
setKeyPool.erase(setKeyPool.begin());
if (!Read(make_pair(string("pool"), nIndex), keypool))
throw runtime_error("ReserveKeyFromKeyPool() : read failed");
if (!mapKeys.count(keypool.vchPubKey))
throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
assert(!keypool.vchPubKey.empty());
printf("keypool reserve %"PRI64d"\n", nIndex);
}
}
void CWalletDB::KeepKey(int64 nIndex)
{
// Remove from key pool
CRITICAL_BLOCK(cs_main)
CRITICAL_BLOCK(cs_mapWallet)
{
Erase(make_pair(string("pool"), nIndex));
}
printf("keypool keep %"PRI64d"\n", nIndex);
}
void CWalletDB::ReturnKey(int64 nIndex)
{
// Return to key pool
CRITICAL_BLOCK(cs_setKeyPool)
setKeyPool.insert(nIndex);
printf("keypool return %"PRI64d"\n", nIndex);
}
vector<unsigned char> GetKeyFromKeyPool()
{
CWalletDB walletdb;
int64 nIndex = 0;
CKeyPool keypool;
walletdb.ReserveKeyFromKeyPool(nIndex, keypool);
walletdb.KeepKey(nIndex);
return keypool.vchPubKey;
}
int64 GetOldestKeyPoolTime()
{
CWalletDB walletdb;
int64 nIndex = 0;
CKeyPool keypool;
walletdb.ReserveKeyFromKeyPool(nIndex, keypool);
walletdb.ReturnKey(nIndex);
return keypool.nTime;
return false;
}

118
src/db.h

@ -12,33 +12,25 @@ @@ -12,33 +12,25 @@
#include <db_cxx.h>
class CTransaction;
class CTxIndex;
class CDiskBlockIndex;
class CDiskTxPos;
class COutPoint;
class CUser;
class CReview;
class CAddress;
class CWalletTx;
class CWallet;
class CAccount;
class CAccountingEntry;
class CBlockLocator;
extern std::map<std::string, std::string> mapAddressBook;
extern CCriticalSection cs_mapAddressBook;
extern std::vector<unsigned char> vchDefaultKey;
extern bool fClient;
extern int nBestHeight;
extern unsigned int nWalletDBUpdated;
extern DbEnv dbenv;
extern void DBFlush(bool fShutdown);
extern std::vector<unsigned char> GetKeyFromKeyPool();
extern int64 GetOldestKeyPoolTime();
void ThreadFlushWalletDB(void* parg);
bool BackupWallet(const CWallet& wallet, const std::string& strDest);
@ -321,9 +313,6 @@ bool LoadAddresses(); @@ -321,9 +313,6 @@ bool LoadAddresses();
class CKeyPool
{
public:
@ -356,7 +345,7 @@ public: @@ -356,7 +345,7 @@ public:
class CWalletDB : public CDB
{
public:
CWalletDB(const char* pszMode="r+") : CDB("wallet.dat", pszMode)
CWalletDB(std::string strFilename, const char* pszMode="r+") : CDB(strFilename.c_str(), pszMode)
{
}
private:
@ -369,23 +358,9 @@ public: @@ -369,23 +358,9 @@ public:
return Read(std::make_pair(std::string("name"), strAddress), strName);
}
bool WriteName(const std::string& strAddress, const std::string& strName)
{
CRITICAL_BLOCK(cs_mapAddressBook)
mapAddressBook[strAddress] = strName;
nWalletDBUpdated++;
return Write(std::make_pair(std::string("name"), strAddress), strName);
}
bool WriteName(const std::string& strAddress, const std::string& strName);
bool EraseName(const std::string& strAddress)
{
// This should only be used for sending addresses, never for receiving addresses,
// receiving addresses must always have an address book entry if they're not change return.
CRITICAL_BLOCK(cs_mapAddressBook)
mapAddressBook.erase(strAddress);
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("name"), strAddress));
}
bool EraseName(const std::string& strAddress);
bool ReadTx(uint256 hash, CWalletTx& wtx)
{
@ -435,11 +410,27 @@ public: @@ -435,11 +410,27 @@ public:
bool WriteDefaultKey(const std::vector<unsigned char>& vchPubKey)
{
vchDefaultKey = vchPubKey;
nWalletDBUpdated++;
return Write(std::string("defaultkey"), vchPubKey);
}
bool ReadPool(int64 nPool, CKeyPool& keypool)
{
return Read(std::make_pair(std::string("pool"), nPool), keypool);
}
bool WritePool(int64 nPool, const CKeyPool& keypool)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("pool"), nPool), keypool);
}
bool ErasePool(int64 nPool)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("pool"), nPool));
}
template<typename T>
bool ReadSetting(const std::string& strKey, T& value)
{
@ -459,68 +450,7 @@ public: @@ -459,68 +450,7 @@ public:
int64 GetAccountCreditDebit(const std::string& strAccount);
void ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& acentries);
bool LoadWallet();
protected:
void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
void KeepKey(int64 nIndex);
static void ReturnKey(int64 nIndex);
friend class CReserveKey;
friend std::vector<unsigned char> GetKeyFromKeyPool();
friend int64 GetOldestKeyPoolTime();
};
bool LoadWallet(bool& fFirstRunRet);
void BackupWallet(const std::string& strDest);
inline bool SetAddressBookName(const std::string& strAddress, const std::string& strName)
{
return CWalletDB().WriteName(strAddress, strName);
}
class CReserveKey
{
protected:
int64 nIndex;
std::vector<unsigned char> vchPubKey;
public:
CReserveKey()
{
nIndex = -1;
}
~CReserveKey()
{
if (!fShutdown)
ReturnKey();
}
std::vector<unsigned char> GetReservedKey()
{
if (nIndex == -1)
{
CKeyPool keypool;
CWalletDB().ReserveKeyFromKeyPool(nIndex, keypool);
vchPubKey = keypool.vchPubKey;
}
assert(!vchPubKey.empty());
return vchPubKey;
}
void KeepKey()
{
if (nIndex != -1)
CWalletDB().KeepKey(nIndex);
nIndex = -1;
vchPubKey.clear();
}
void ReturnKey()
{
if (nIndex != -1)
CWalletDB::ReturnKey(nIndex);
nIndex = -1;
vchPubKey.clear();
}
bool LoadWallet(CWallet* pwallet);
};
#endif

2
src/headers.h

@ -91,10 +91,8 @@ @@ -91,10 +91,8 @@
#include "serialize.h"
#include "uint256.h"
#include "util.h"
#include "key.h"
#include "bignum.h"
#include "base58.h"
#include "script.h"
#include "main.h"
#ifdef GUI
#include "uibase.h"

22
src/init.cpp

@ -13,6 +13,8 @@ @@ -13,6 +13,8 @@
using namespace std;
using namespace boost;
CWallet* pwalletMain;
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
@ -45,6 +47,8 @@ void Shutdown(void* parg) @@ -45,6 +47,8 @@ void Shutdown(void* parg)
StopNode();
DBFlush(true);
boost::filesystem::remove(GetPidFile());
UnregisterWallet(pwalletMain);
delete pwalletMain;
CreateThread(ExitTimeout, NULL);
Sleep(50);
printf("Bitcoin exiting\n\n");
@ -372,16 +376,19 @@ bool AppInit2(int argc, char* argv[]) @@ -372,16 +376,19 @@ bool AppInit2(int argc, char* argv[])
printf("Loading wallet...\n");
nStart = GetTimeMillis();
bool fFirstRun;
if (!LoadWallet(fFirstRun))
pwalletMain = new CWallet("wallet.dat");
if (!pwalletMain->LoadWallet(fFirstRun))
strErrors += _("Error loading wallet.dat \n");
printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
RegisterWallet(pwalletMain);
CBlockIndex *pindexRescan = pindexBest;
if (GetBoolArg("-rescan"))
pindexRescan = pindexGenesisBlock;
else
{
CWalletDB walletdb;
CWalletDB walletdb("wallet.dat");
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = locator.GetBlockIndex();
@ -390,7 +397,7 @@ bool AppInit2(int argc, char* argv[]) @@ -390,7 +397,7 @@ bool AppInit2(int argc, char* argv[])
{
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
ScanForWalletTransactions(pindexRescan, true);
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
}
@ -399,10 +406,11 @@ bool AppInit2(int argc, char* argv[]) @@ -399,10 +406,11 @@ bool AppInit2(int argc, char* argv[])
//// debug print
printf("mapBlockIndex.size() = %d\n", mapBlockIndex.size());
printf("nBestHeight = %d\n", nBestHeight);
printf("mapKeys.size() = %d\n", mapKeys.size());
printf("mapKeys.size() = %d\n", pwalletMain->mapKeys.size());
printf("setKeyPool.size() = %d\n", pwalletMain->setKeyPool.size());
printf("mapPubKeys.size() = %d\n", mapPubKeys.size());
printf("mapWallet.size() = %d\n", mapWallet.size());
printf("mapAddressBook.size() = %d\n", mapAddressBook.size());
printf("mapWallet.size() = %d\n", pwalletMain->mapWallet.size());
printf("mapAddressBook.size() = %d\n", pwalletMain->mapAddressBook.size());
if (!strErrors.empty())
{
@ -411,7 +419,7 @@ bool AppInit2(int argc, char* argv[]) @@ -411,7 +419,7 @@ bool AppInit2(int argc, char* argv[])
}
// Add wallet transactions that aren't already in a block to mapTransactions
ReacceptWalletTransactions();
pwalletMain->ReacceptWalletTransactions();
//
// Parameters

2
src/init.h

@ -4,6 +4,8 @@ @@ -4,6 +4,8 @@
#ifndef BITCOIN_INIT_H
#define BITCOIN_INIT_H
extern CWallet* pwalletMain;
void Shutdown(void* parg);
bool AppInit(int argc, char* argv[]);
bool AppInit2(int argc, char* argv[]);

33
src/keystore.cpp

@ -0,0 +1,33 @@ @@ -0,0 +1,33 @@
// Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "headers.h"
#include "db.h"
//////////////////////////////////////////////////////////////////////////////
//
// mapKeys
//
std::vector<unsigned char> CKeyStore::GenerateNewKey()
{
RandAddSeedPerfmon();
CKey key;
key.MakeNewKey();
if (!AddKey(key))
throw std::runtime_error("GenerateNewKey() : AddKey failed");
return key.GetPubKey();
}
bool CKeyStore::AddKey(const CKey& key)
{
CRITICAL_BLOCK(cs_mapKeys)
{
mapKeys[key.GetPubKey()] = key.GetPrivKey();
mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
}
}

26
src/keystore.h

@ -0,0 +1,26 @@ @@ -0,0 +1,26 @@
// Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_KEYSTORE_H
#define BITCOIN_KEYSTORE_H
class CKeyStore
{
public:
std::map<std::vector<unsigned char>, CPrivKey> mapKeys;
mutable CCriticalSection cs_mapKeys;
virtual bool AddKey(const CKey& key);
bool HaveKey(const std::vector<unsigned char> &vchPubKey) const
{
return (mapKeys.count(vchPubKey) > 0);
}
CPrivKey GetPrivKey(const std::vector<unsigned char> &vchPubKey) const
{
std::map<std::vector<unsigned char>, CPrivKey>::const_iterator mi = mapKeys.find(vchPubKey);
if (mi != mapKeys.end())
return (*mi).second;
}
std::vector<unsigned char> GenerateNewKey();
};
#endif

1441
src/main.cpp

File diff suppressed because it is too large Load Diff

567
src/main.h

@ -7,22 +7,18 @@ @@ -7,22 +7,18 @@
#include "bignum.h"
#include "net.h"
#include "key.h"
#include "db.h"
#include "script.h"
#include "db.h"
#include <list>
class COutPoint;
class CInPoint;
class CDiskTxPos;
class CCoinBase;
class CTxIn;
class CTxOut;
class CTransaction;
class CBlock;
class CBlockIndex;
class CWalletTx;
class CWallet;
class CKeyItem;
class CReserveKey;
class CWalletDB;
class CMessageHeader;
class CAddress;
@ -63,13 +59,11 @@ extern CBigNum bnBestInvalidWork; @@ -63,13 +59,11 @@ extern CBigNum bnBestInvalidWork;
extern uint256 hashBestChain;
extern CBlockIndex* pindexBest;
extern unsigned int nTransactionsUpdated;
extern std::map<uint256, int> mapRequestCount;
extern CCriticalSection cs_mapRequestCount;
extern std::map<std::string, std::string> mapAddressBook;
extern CCriticalSection cs_mapAddressBook;
extern std::vector<unsigned char> vchDefaultKey;
extern double dHashesPerSec;
extern int64 nHPSTimerStart;
extern int64 nTimeBestReceived;
extern CCriticalSection cs_setpwalletRegistered;
extern std::set<CWallet*> setpwalletRegistered;
// Settings
extern int fGenerateBitcoins;
@ -89,34 +83,20 @@ class CReserveKey; @@ -89,34 +83,20 @@ class CReserveKey;
class CTxDB;
class CTxIndex;
void RegisterWallet(CWallet* pwalletIn);
void UnregisterWallet(CWallet* pwalletIn);
bool CheckDiskSpace(uint64 nAdditionalBytes=0);
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
FILE* AppendBlockFile(unsigned int& nFileRet);
bool AddKey(const CKey& key);
std::vector<unsigned char> GenerateNewKey();
bool AddToWallet(const CWalletTx& wtxIn);
void WalletUpdateSpent(const COutPoint& prevout);
int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
void ReacceptWalletTransactions();
bool LoadBlockIndex(bool fAllowNew=true);
void PrintBlockTree();
bool ProcessMessages(CNode* pfrom);
bool ProcessMessage(CNode* pfrom, std::string strCommand, CDataStream& vRecv);
bool SendMessages(CNode* pto, bool fSendTrickle);
int64 GetBalance();
bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
bool BroadcastTransaction(CWalletTx& wtxNew);
std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
std::string SendMoneyToBitcoinAddress(std::string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
void GenerateBitcoins(bool fGenerate);
void ThreadBitcoinMiner(void* parg);
void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
CBlock* CreateNewBlock(CReserveKey& reservekey);
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime);
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
bool CheckWork(CBlock* pblock, CReserveKey& reservekey);
void BitcoinMiner();
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
bool CheckProofOfWork(uint256 hash, unsigned int nBits);
bool IsInitialBlockDownload();
std::string GetWarnings(std::string strFor);
@ -132,6 +112,23 @@ std::string GetWarnings(std::string strFor); @@ -132,6 +112,23 @@ std::string GetWarnings(std::string strFor);
bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
template<typename T>
bool WriteSetting(const std::string& strKey, const T& value)
{
bool fOk = false;
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
{
std::string strWalletFile;
if (!GetWalletFile(pwallet, strWalletFile))
continue;
fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
}
return fOk;
}
class CDiskTxPos
{
public:
@ -314,9 +311,6 @@ public: @@ -314,9 +311,6 @@ public:
{
printf("%s\n", ToString().c_str());
}
bool IsMine() const;
int64 GetDebit() const;
};
@ -365,36 +359,6 @@ public: @@ -365,36 +359,6 @@ public:
return SerializeHash(*this);
}
bool IsMine() const
{
return ::IsMine(scriptPubKey);
}
int64 GetCredit() const
{
if (!MoneyRange(nValue))
throw std::runtime_error("CTxOut::GetCredit() : value out of range");
return (IsMine() ? nValue : 0);
}
bool IsChange() const
{
// On a debit transaction, a txout that's mine but isn't in the address book is change
std::vector<unsigned char> vchPubKey;
if (ExtractPubKey(scriptPubKey, true, vchPubKey))
CRITICAL_BLOCK(cs_mapAddressBook)
if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
return true;
return false;
}
int64 GetChange() const
{
if (!MoneyRange(nValue))
throw std::runtime_error("CTxOut::GetChange() : value out of range");
return (IsChange() ? nValue : 0);
}
friend bool operator==(const CTxOut& a, const CTxOut& b)
{
return (a.nValue == b.nValue &&
@ -539,57 +503,6 @@ public: @@ -539,57 +503,6 @@ public:
return true;
}
bool IsMine() const
{
BOOST_FOREACH(const CTxOut& txout, vout)
if (txout.IsMine())
return true;
return false;
}
bool IsFromMe() const
{
return (GetDebit() > 0);
}
int64 GetDebit() const
{
int64 nDebit = 0;
BOOST_FOREACH(const CTxIn& txin, vin)
{
nDebit += txin.GetDebit();
if (!MoneyRange(nDebit))
throw std::runtime_error("CTransaction::GetDebit() : value out of range");
}
return nDebit;
}
int64 GetCredit() const
{
int64 nCredit = 0;
BOOST_FOREACH(const CTxOut& txout, vout)
{
nCredit += txout.GetCredit();
if (!MoneyRange(nCredit))
throw std::runtime_error("CTransaction::GetCredit() : value out of range");
}
return nCredit;
}
int64 GetChange() const
{
if (IsCoinBase())
return 0;
int64 nChange = 0;
BOOST_FOREACH(const CTxOut& txout, vout)
{
nChange += txout.GetChange();
if (!MoneyRange(nChange))
throw std::runtime_error("CTransaction::GetChange() : value out of range");
}
return nChange;
}
int64 GetValueOut() const
{
int64 nValueOut = 0;
@ -721,11 +634,7 @@ public: @@ -721,11 +634,7 @@ public:
bool ClientConnectInputs();
bool CheckTransaction() const;
bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
{
CTxDB txdb("r");
return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
}
bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
protected:
bool AddToMemoryPoolUnchecked();
public:
@ -784,307 +693,7 @@ public: @@ -784,307 +693,7 @@ public:
bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
int GetBlocksToMaturity() const;
bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
};
//
// A transaction with a bunch of additional info that only the owner cares
// about. It includes any unrecorded transactions needed to link it back
// to the block chain.
//
class CWalletTx : public CMerkleTx
{
public:
std::vector<CMerkleTx> vtxPrev;
std::map<std::string, std::string> mapValue;
std::vector<std::pair<std::string, std::string> > vOrderForm;
unsigned int fTimeReceivedIsTxTime;
unsigned int nTimeReceived; // time received by this node
char fFromMe;
std::string strFromAccount;
std::vector<char> vfSpent;
// memory only
mutable char fDebitCached;
mutable char fCreditCached;
mutable char fAvailableCreditCached;
mutable char fChangeCached;
mutable int64 nDebitCached;
mutable int64 nCreditCached;
mutable int64 nAvailableCreditCached;
mutable int64 nChangeCached;
// memory only UI hints
mutable unsigned int nTimeDisplayed;
mutable int nLinesDisplayed;
mutable char fConfirmedDisplayed;
CWalletTx()
{
Init();
}
CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
{
Init();
}
CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
{
Init();
}
void Init()
{
vtxPrev.clear();
mapValue.clear();
vOrderForm.clear();
fTimeReceivedIsTxTime = false;
nTimeReceived = 0;
fFromMe = false;
strFromAccount.clear();
vfSpent.clear();
fDebitCached = false;
fCreditCached = false;
fAvailableCreditCached = false;
fChangeCached = false;
nDebitCached = 0;
nCreditCached = 0;
nAvailableCreditCached = 0;
nChangeCached = 0;
nTimeDisplayed = 0;
nLinesDisplayed = 0;
fConfirmedDisplayed = false;
}
IMPLEMENT_SERIALIZE
(
CWalletTx* pthis = const_cast<CWalletTx*>(this);
if (fRead)
pthis->Init();
char fSpent = false;
if (!fRead)
{
pthis->mapValue["fromaccount"] = pthis->strFromAccount;
std::string str;
BOOST_FOREACH(char f, vfSpent)
{
str += (f ? '1' : '0');
if (f)
fSpent = true;
}
pthis->mapValue["spent"] = str;
}
nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
READWRITE(vtxPrev);
READWRITE(mapValue);
READWRITE(vOrderForm);
READWRITE(fTimeReceivedIsTxTime);
READWRITE(nTimeReceived);
READWRITE(fFromMe);
READWRITE(fSpent);
if (fRead)
{
pthis->strFromAccount = pthis->mapValue["fromaccount"];
if (mapValue.count("spent"))
BOOST_FOREACH(char c, pthis->mapValue["spent"])
pthis->vfSpent.push_back(c != '0');
else
pthis->vfSpent.assign(vout.size(), fSpent);
}
pthis->mapValue.erase("fromaccount");
pthis->mapValue.erase("version");
pthis->mapValue.erase("spent");
)
// marks certain txout's as spent
// returns true if any update took place
bool UpdateSpent(const std::vector<char>& vfNewSpent)
{
bool fReturn = false;
for (int i=0; i < vfNewSpent.size(); i++)
{
if (i == vfSpent.size())
break;
if (vfNewSpent[i] && !vfSpent[i])
{
vfSpent[i] = true;
fReturn = true;
fAvailableCreditCached = false;
}
}
return fReturn;
}
void MarkDirty()
{
fCreditCached = false;
fAvailableCreditCached = false;
fDebitCached = false;
fChangeCached = false;
}
void MarkSpent(unsigned int nOut)
{
if (nOut >= vout.size())
throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
vfSpent.resize(vout.size());
if (!vfSpent[nOut])
{
vfSpent[nOut] = true;
fAvailableCreditCached = false;
}
}
bool IsSpent(unsigned int nOut) const
{
if (nOut >= vout.size())
throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
if (nOut >= vfSpent.size())
return false;
return (!!vfSpent[nOut]);
}
int64 GetDebit() const
{
if (vin.empty())
return 0;
if (fDebitCached)
return nDebitCached;
nDebitCached = CTransaction::GetDebit();
fDebitCached = true;
return nDebitCached;
}
int64 GetCredit(bool fUseCache=true) const
{
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
// GetBalance can assume transactions in mapWallet won't change
if (fUseCache && fCreditCached)
return nCreditCached;
nCreditCached = CTransaction::GetCredit();
fCreditCached = true;
return nCreditCached;
}
int64 GetAvailableCredit(bool fUseCache=true) const
{
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
if (fUseCache && fAvailableCreditCached)
return nAvailableCreditCached;
int64 nCredit = 0;
for (int i = 0; i < vout.size(); i++)
{
if (!IsSpent(i))
{
const CTxOut &txout = vout[i];
nCredit += txout.GetCredit();
if (!MoneyRange(nCredit))
throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
}
}
nAvailableCreditCached = nCredit;
fAvailableCreditCached = true;
return nCredit;
}
int64 GetChange() const
{
if (fChangeCached)
return nChangeCached;
nChangeCached = CTransaction::GetChange();
fChangeCached = true;
return nChangeCached;
}
void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
int64& nSent, int64& nFee) const;
bool IsFromMe() const
{
return (GetDebit() > 0);
}
bool IsConfirmed() const
{
// Quick answer in most cases
if (!IsFinal())
return false;
if (GetDepthInMainChain() >= 1)
return true;
if (!IsFromMe()) // using wtx's cached debit
return false;
// If no confirmations but it's from us, we can still
// consider it confirmed if all dependencies are confirmed
std::map<uint256, const CMerkleTx*> mapPrev;
std::vector<const CMerkleTx*> vWorkQueue;
vWorkQueue.reserve(vtxPrev.size()+1);
vWorkQueue.push_back(this);
for (int i = 0; i < vWorkQueue.size(); i++)
{
const CMerkleTx* ptx = vWorkQueue[i];
if (!ptx->IsFinal())
return false;
if (ptx->GetDepthInMainChain() >= 1)
continue;
if (!ptx->IsFromMe())
return false;
if (mapPrev.empty())
BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
mapPrev[tx.GetHash()] = &tx;
BOOST_FOREACH(const CTxIn& txin, ptx->vin)
{
if (!mapPrev.count(txin.prevout.hash))
return false;
vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
}
}
return true;
}
bool WriteToDisk()
{
return CWalletDB().WriteTx(GetHash(), *this);
}
int64 GetTxTime() const;
int GetRequestCount() const;
void AddSupportingTransactions(CTxDB& txdb);
bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
void RelayWalletTransaction(CTxDB& txdb);
void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
bool AcceptToMemoryPool();
};
@ -1744,114 +1353,6 @@ public: @@ -1744,114 +1353,6 @@ public:
//
// Private key that includes an expiration date in case it never gets used.
//
class CWalletKey
{
public:
CPrivKey vchPrivKey;
int64 nTimeCreated;
int64 nTimeExpires;
std::string strComment;
//// todo: add something to note what created it (user, getnewaddress, change)
//// maybe should have a map<string, string> property map
CWalletKey(int64 nExpires=0)
{
nTimeCreated = (nExpires ? GetTime() : 0);
nTimeExpires = nExpires;
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vchPrivKey);
READWRITE(nTimeCreated);
READWRITE(nTimeExpires);
READWRITE(strComment);
)
};
//
// Account information.
// Stored in wallet with key "acc"+string account name
//
class CAccount
{
public:
std::vector<unsigned char> vchPubKey;
CAccount()
{
SetNull();
}
void SetNull()
{
vchPubKey.clear();
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vchPubKey);
)
};
//
// Internal transfers.
// Database key is acentry<account><counter>
//
class CAccountingEntry
{
public:
std::string strAccount;
int64 nCreditDebit;
int64 nTime;
std::string strOtherAccount;
std::string strComment;
CAccountingEntry()
{
SetNull();
}
void SetNull()
{
nCreditDebit = 0;
nTime = 0;
strAccount.clear();
strOtherAccount.clear();
strComment.clear();
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
// Note: strAccount is serialized as part of the key, not here.
READWRITE(nCreditDebit);
READWRITE(nTime);
READWRITE(strOtherAccount);
READWRITE(strComment);
)
};
@ -2063,13 +1564,9 @@ public: @@ -2063,13 +1564,9 @@ public:
extern std::map<uint256, CTransaction> mapTransactions;
extern std::map<uint256, CWalletTx> mapWallet;
extern std::vector<uint256> vWalletUpdated;
extern CCriticalSection cs_mapWallet;
extern std::map<std::vector<unsigned char>, CPrivKey> mapKeys;
extern std::map<uint160, std::vector<unsigned char> > mapPubKeys;
extern CCriticalSection cs_mapKeys;
extern CKey keyUser;
extern CCriticalSection cs_mapPubKeys;
#endif

4
src/makefile.mingw

@ -33,7 +33,7 @@ DEFS=-DWIN32 -D__WXMSW__ -D_WINDOWS -DNOPCH -DUSE_SSL @@ -33,7 +33,7 @@ DEFS=-DWIN32 -D__WXMSW__ -D_WINDOWS -DNOPCH -DUSE_SSL
DEBUGFLAGS=-g -D__WXDEBUG__
CFLAGS=-mthreads -O2 -w -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(DEFS) $(INCLUDEPATHS)
HEADERS=headers.h strlcpy.h serialize.h uint256.h util.h key.h bignum.h base58.h \
script.h db.h net.h irc.h main.h rpc.h uibase.h ui.h noui.h init.h
script.h db.h net.h irc.h keystore.h main.h wallet.h rpc.h uibase.h ui.h noui.h init.h
ifdef USE_UPNP
INCLUDEPATHS += -I"C:\upnpc-exe-win32-20110215"
@ -50,7 +50,9 @@ OBJS= \ @@ -50,7 +50,9 @@ OBJS= \
obj/db.o \
obj/net.o \
obj/irc.o \
obj/keystore.o \
obj/main.o \
obj/wallet.o \
obj/rpc.o \
obj/init.o \
cryptopp/obj/sha.o \

4
src/makefile.osx vendored

@ -33,7 +33,7 @@ DEBUGFLAGS=-g -DwxDEBUG_LEVEL=0 @@ -33,7 +33,7 @@ DEBUGFLAGS=-g -DwxDEBUG_LEVEL=0
# ppc doesn't work because we don't support big-endian
CFLAGS=-mmacosx-version-min=10.5 -arch i386 -arch x86_64 -O3 -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(DEFS) $(INCLUDEPATHS)
HEADERS=headers.h strlcpy.h serialize.h uint256.h util.h key.h bignum.h base58.h \
script.h db.h net.h irc.h main.h rpc.h uibase.h ui.h noui.h init.h
script.h db.h net.h irc.h keystore.h main.h wallet.h rpc.h uibase.h ui.h noui.h init.h
OBJS= \
obj/util.o \
@ -41,7 +41,9 @@ OBJS= \ @@ -41,7 +41,9 @@ OBJS= \
obj/db.o \
obj/net.o \
obj/irc.o \
obj/keystore.o \
obj/main.o \
obj/wallet.o \
obj/rpc.o \
obj/init.o \
cryptopp/obj/sha.o \

4
src/makefile.unix

@ -39,7 +39,7 @@ LIBS+= \ @@ -39,7 +39,7 @@ LIBS+= \
DEBUGFLAGS=-g -D__WXDEBUG__
CXXFLAGS=-O2 -Wno-invalid-offsetof -Wformat $(DEBUGFLAGS) $(DEFS)
HEADERS=headers.h strlcpy.h serialize.h uint256.h util.h key.h bignum.h base58.h \
script.h db.h net.h irc.h main.h rpc.h uibase.h ui.h noui.h init.h
script.h db.h net.h irc.h keystore.h main.h wallet.h rpc.h uibase.h ui.h noui.h init.h
OBJS= \
obj/util.o \
@ -47,7 +47,9 @@ OBJS= \ @@ -47,7 +47,9 @@ OBJS= \
obj/db.o \
obj/net.o \
obj/irc.o \
obj/keystore.o \
obj/main.o \
obj/wallet.o \
obj/rpc.o \
obj/init.o \
cryptopp/obj/sha.o \

4
src/net.cpp

@ -1117,7 +1117,7 @@ void MapPort(bool fMapPort) @@ -1117,7 +1117,7 @@ void MapPort(bool fMapPort)
if (fUseUPnP != fMapPort)
{
fUseUPnP = fMapPort;
CWalletDB().WriteSetting("fUseUPnP", fUseUPnP);
WriteSetting("fUseUPnP", fUseUPnP);
}
if (fUseUPnP && vnThreadsRunning[5] < 1)
{
@ -1698,7 +1698,7 @@ void StartNode(void* parg) @@ -1698,7 +1698,7 @@ void StartNode(void* parg)
printf("Error: CreateThread(ThreadMessageHandler) failed\n");
// Generate coins in the background
GenerateBitcoins(fGenerateBitcoins);
GenerateBitcoins(fGenerateBitcoins, pwalletMain);
}
bool StopNode()

2
src/noui.h

@ -5,6 +5,8 @@ @@ -5,6 +5,8 @@
#define BITCOIN_NOUI_H
#include <string>
#include <boost/function.hpp>
#include "wallet.h"
typedef void wxWindow;
#define wxYES 0x00000002

148
src/rpc.cpp

@ -264,14 +264,14 @@ Value setgenerate(const Array& params, bool fHelp) @@ -264,14 +264,14 @@ Value setgenerate(const Array& params, bool fHelp)
{
int nGenProcLimit = params[1].get_int();
fLimitProcessors = (nGenProcLimit != -1);
CWalletDB().WriteSetting("fLimitProcessors", fLimitProcessors);
WriteSetting("fLimitProcessors", fLimitProcessors);
if (nGenProcLimit != -1)
CWalletDB().WriteSetting("nLimitProcessors", nLimitProcessors = nGenProcLimit);
WriteSetting("nLimitProcessors", nLimitProcessors = nGenProcLimit);
if (nGenProcLimit == 0)
fGenerate = false;
}
GenerateBitcoins(fGenerate);
GenerateBitcoins(fGenerate, pwalletMain);
return Value::null;
}
@ -298,7 +298,7 @@ Value getinfo(const Array& params, bool fHelp) @@ -298,7 +298,7 @@ Value getinfo(const Array& params, bool fHelp)
Object obj;
obj.push_back(Pair("version", (int)VERSION));
obj.push_back(Pair("balance", ValueFromAmount(GetBalance())));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (fUseProxy ? addrProxy.ToStringIPPort() : string())));
@ -307,7 +307,7 @@ Value getinfo(const Array& params, bool fHelp) @@ -307,7 +307,7 @@ Value getinfo(const Array& params, bool fHelp)
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
obj.push_back(Pair("testnet", fTestNet));
obj.push_back(Pair("keypoololdest", (boost::int64_t)GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
@ -329,9 +329,9 @@ Value getnewaddress(const Array& params, bool fHelp) @@ -329,9 +329,9 @@ Value getnewaddress(const Array& params, bool fHelp)
strAccount = AccountFromValue(params[0]);
// Generate a new key that is added to wallet
string strAddress = PubKeyToAddress(GetKeyFromKeyPool());
string strAddress = PubKeyToAddress(pwalletMain->GetKeyFromKeyPool());
SetAddressBookName(strAddress, strAccount);
pwalletMain->SetAddressBookName(strAddress, strAccount);
return strAddress;
}
@ -341,7 +341,7 @@ string GetAccountAddress(string strAccount, bool bForceNew=false) @@ -341,7 +341,7 @@ string GetAccountAddress(string strAccount, bool bForceNew=false)
{
string strAddress;
CWalletDB walletdb;
CWalletDB walletdb(pwalletMain->strWalletFile);
walletdb.TxnBegin();
CAccount account;
@ -352,8 +352,8 @@ string GetAccountAddress(string strAccount, bool bForceNew=false) @@ -352,8 +352,8 @@ string GetAccountAddress(string strAccount, bool bForceNew=false)
{
CScript scriptPubKey;
scriptPubKey.SetBitcoinAddress(account.vchPubKey);
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin();
it != mapWallet.end() && !account.vchPubKey.empty();
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && !account.vchPubKey.empty();
++it)
{
const CWalletTx& wtx = (*it).second;
@ -366,9 +366,9 @@ string GetAccountAddress(string strAccount, bool bForceNew=false) @@ -366,9 +366,9 @@ string GetAccountAddress(string strAccount, bool bForceNew=false)
// Generate a new key
if (account.vchPubKey.empty() || bForceNew)
{
account.vchPubKey = GetKeyFromKeyPool();
account.vchPubKey = pwalletMain->GetKeyFromKeyPool();
string strAddress = PubKeyToAddress(account.vchPubKey);
SetAddressBookName(strAddress, strAccount);
pwalletMain->SetAddressBookName(strAddress, strAccount);
walletdb.WriteAccount(strAccount, account);
}
@ -391,7 +391,7 @@ Value getaccountaddress(const Array& params, bool fHelp) @@ -391,7 +391,7 @@ Value getaccountaddress(const Array& params, bool fHelp)
Value ret;
CRITICAL_BLOCK(cs_main)
CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
ret = GetAccountAddress(strAccount);
}
@ -421,18 +421,18 @@ Value setaccount(const Array& params, bool fHelp) @@ -421,18 +421,18 @@ Value setaccount(const Array& params, bool fHelp)
// Detect when changing the account of an address that is the 'unused current key' of another account:
CRITICAL_BLOCK(cs_main)
CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(cs_mapAddressBook)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
if (mapAddressBook.count(strAddress))
if (pwalletMain->mapAddressBook.count(strAddress))
{
string strOldAccount = mapAddressBook[strAddress];
string strOldAccount = pwalletMain->mapAddressBook[strAddress];
if (strAddress == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
}
SetAddressBookName(strAddress, strAccount);
pwalletMain->SetAddressBookName(strAddress, strAccount);
return Value::null;
}
@ -447,10 +447,10 @@ Value getaccount(const Array& params, bool fHelp) @@ -447,10 +447,10 @@ Value getaccount(const Array& params, bool fHelp)
string strAddress = params[0].get_str();
string strAccount;
CRITICAL_BLOCK(cs_mapAddressBook)
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
map<string, string>::iterator mi = mapAddressBook.find(strAddress);
if (mi != mapAddressBook.end() && !(*mi).second.empty())
map<string, string>::iterator mi = pwalletMain->mapAddressBook.find(strAddress);
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
strAccount = (*mi).second;
}
return strAccount;
@ -468,9 +468,9 @@ Value getaddressesbyaccount(const Array& params, bool fHelp) @@ -468,9 +468,9 @@ Value getaddressesbyaccount(const Array& params, bool fHelp)
// Find all addresses that have the given account
Array ret;
CRITICAL_BLOCK(cs_mapAddressBook)
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
BOOST_FOREACH(const PAIRTYPE(string, string)& item, pwalletMain->mapAddressBook)
{
const string& strAddress = item.first;
const string& strName = item.second;
@ -523,7 +523,7 @@ Value sendtoaddress(const Array& params, bool fHelp) @@ -523,7 +523,7 @@ Value sendtoaddress(const Array& params, bool fHelp)
CRITICAL_BLOCK(cs_main)
{
string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
string strError = pwalletMain->SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
if (strError != "")
throw JSONRPCError(-4, strError);
}
@ -544,7 +544,7 @@ Value getreceivedbyaddress(const Array& params, bool fHelp) @@ -544,7 +544,7 @@ Value getreceivedbyaddress(const Array& params, bool fHelp)
CScript scriptPubKey;
if (!scriptPubKey.SetBitcoinAddress(strAddress))
throw JSONRPCError(-5, "Invalid bitcoin address");
if (!IsMine(scriptPubKey))
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
@ -554,9 +554,9 @@ Value getreceivedbyaddress(const Array& params, bool fHelp) @@ -554,9 +554,9 @@ Value getreceivedbyaddress(const Array& params, bool fHelp)
// Tally
int64 nAmount = 0;
CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
@ -575,9 +575,9 @@ Value getreceivedbyaddress(const Array& params, bool fHelp) @@ -575,9 +575,9 @@ Value getreceivedbyaddress(const Array& params, bool fHelp)
void GetAccountPubKeys(string strAccount, set<CScript>& setPubKey)
{
CRITICAL_BLOCK(cs_mapAddressBook)
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
BOOST_FOREACH(const PAIRTYPE(string, string)& item, pwalletMain->mapAddressBook)
{
const string& strAddress = item.first;
const string& strName = item.second;
@ -586,7 +586,7 @@ void GetAccountPubKeys(string strAccount, set<CScript>& setPubKey) @@ -586,7 +586,7 @@ void GetAccountPubKeys(string strAccount, set<CScript>& setPubKey)
// We're only counting our own valid bitcoin addresses and not ip addresses
CScript scriptPubKey;
if (scriptPubKey.SetBitcoinAddress(strAddress))
if (IsMine(scriptPubKey))
if (IsMine(*pwalletMain,scriptPubKey))
setPubKey.insert(scriptPubKey);
}
}
@ -613,9 +613,9 @@ Value getreceivedbyaccount(const Array& params, bool fHelp) @@ -613,9 +613,9 @@ Value getreceivedbyaccount(const Array& params, bool fHelp)
// Tally
int64 nAmount = 0;
CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
@ -635,10 +635,10 @@ Value getreceivedbyaccount(const Array& params, bool fHelp) @@ -635,10 +635,10 @@ Value getreceivedbyaccount(const Array& params, bool fHelp)
int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
{
int64 nBalance = 0;
CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal())
@ -661,7 +661,7 @@ int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinD @@ -661,7 +661,7 @@ int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinD
int64 GetAccountBalance(const string& strAccount, int nMinDepth)
{
CWalletDB walletdb;
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth);
}
@ -675,7 +675,7 @@ Value getbalance(const Array& params, bool fHelp) @@ -675,7 +675,7 @@ Value getbalance(const Array& params, bool fHelp)
"If [account] is specified, returns the balance in the account.");
if (params.size() == 0)
return ValueFromAmount(GetBalance());
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
@ -686,7 +686,7 @@ Value getbalance(const Array& params, bool fHelp) @@ -686,7 +686,7 @@ Value getbalance(const Array& params, bool fHelp)
// (GetBalance() sums up all unspent TxOuts)
// getbalance and getbalance '*' should always return the same number.
int64 nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal())
@ -734,9 +734,9 @@ Value movecmd(const Array& params, bool fHelp) @@ -734,9 +734,9 @@ Value movecmd(const Array& params, bool fHelp)
if (params.size() > 4)
strComment = params[4].get_str();
CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
CWalletDB walletdb;
CWalletDB walletdb(pwalletMain->strWalletFile);
walletdb.TxnBegin();
int64 nNow = GetAdjustedTime();
@ -787,7 +787,7 @@ Value sendfrom(const Array& params, bool fHelp) @@ -787,7 +787,7 @@ Value sendfrom(const Array& params, bool fHelp)
wtx.mapValue["to"] = params[5].get_str();
CRITICAL_BLOCK(cs_main)
CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
@ -795,7 +795,7 @@ Value sendfrom(const Array& params, bool fHelp) @@ -795,7 +795,7 @@ Value sendfrom(const Array& params, bool fHelp)
throw JSONRPCError(-6, "Account has insufficient funds");
// Send
string strError = SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
string strError = pwalletMain->SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
if (strError != "")
throw JSONRPCError(-4, strError);
}
@ -844,7 +844,7 @@ Value sendmany(const Array& params, bool fHelp) @@ -844,7 +844,7 @@ Value sendmany(const Array& params, bool fHelp)
}
CRITICAL_BLOCK(cs_main)
CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
@ -852,16 +852,16 @@ Value sendmany(const Array& params, bool fHelp) @@ -852,16 +852,16 @@ Value sendmany(const Array& params, bool fHelp)
throw JSONRPCError(-6, "Account has insufficient funds");
// Send
CReserveKey keyChange;
CReserveKey keyChange(pwalletMain);
int64 nFeeRequired = 0;
bool fCreated = CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
if (!fCreated)
{
if (totalAmount + nFeeRequired > GetBalance())
if (totalAmount + nFeeRequired > pwalletMain->GetBalance())
throw JSONRPCError(-6, "Insufficient funds");
throw JSONRPCError(-4, "Transaction creation failed");
}
if (!CommitTransaction(wtx, keyChange))
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(-4, "Transaction commit failed");
}
@ -894,9 +894,9 @@ Value ListReceived(const Array& params, bool fByAccounts) @@ -894,9 +894,9 @@ Value ListReceived(const Array& params, bool fByAccounts)
// Tally
map<uint160, tallyitem> mapTally;
CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
@ -923,9 +923,9 @@ Value ListReceived(const Array& params, bool fByAccounts) @@ -923,9 +923,9 @@ Value ListReceived(const Array& params, bool fByAccounts)
// Reply
Array ret;
map<string, tallyitem> mapAccountTally;
CRITICAL_BLOCK(cs_mapAddressBook)
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
BOOST_FOREACH(const PAIRTYPE(string, string)& item, pwalletMain->mapAddressBook)
{
const string& strAddress = item.first;
const string& strAccount = item.second;
@ -1061,13 +1061,13 @@ void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDe @@ -1061,13 +1061,13 @@ void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDe
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
CRITICAL_BLOCK(cs_mapAddressBook)
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)
{
string account;
if (mapAddressBook.count(r.first))
account = mapAddressBook[r.first];
if (pwalletMain->mapAddressBook.count(r.first))
account = pwalletMain->mapAddressBook[r.first];
if (fAllAccounts || (account == strAccount))
{
Object entry;
@ -1119,16 +1119,16 @@ Value listtransactions(const Array& params, bool fHelp) @@ -1119,16 +1119,16 @@ Value listtransactions(const Array& params, bool fHelp)
nFrom = params[2].get_int();
Array ret;
CWalletDB walletdb;
CWalletDB walletdb(pwalletMain->strWalletFile);
CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
// Firs: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap:
typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef multimap<int64, TxPair > TxItems;
TxItems txByTime;
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
CWalletTx* wtx = &((*it).second);
txByTime.insert(make_pair(wtx->GetTxTime(), TxPair(wtx, (CAccountingEntry*)0)));
@ -1180,16 +1180,16 @@ Value listaccounts(const Array& params, bool fHelp) @@ -1180,16 +1180,16 @@ Value listaccounts(const Array& params, bool fHelp)
nMinDepth = params[0].get_int();
map<string, int64> mapAccountBalances;
CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(cs_mapAddressBook)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
BOOST_FOREACH(const PAIRTYPE(string, string)& entry, mapAddressBook) {
BOOST_FOREACH(const PAIRTYPE(string, string)& entry, pwalletMain->mapAddressBook) {
uint160 hash160;
if(AddressToHash160(entry.first, hash160) && mapPubKeys.count(hash160)) // This address belongs to me
mapAccountBalances[entry.second] = 0;
}
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
int64 nGeneratedImmature, nGeneratedMature, nFee;
@ -1204,8 +1204,8 @@ Value listaccounts(const Array& params, bool fHelp) @@ -1204,8 +1204,8 @@ Value listaccounts(const Array& params, bool fHelp)
{
mapAccountBalances[""] += nGeneratedMature;
BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)
if (mapAddressBook.count(r.first))
mapAccountBalances[mapAddressBook[r.first]] += r.second;
if (pwalletMain->mapAddressBook.count(r.first))
mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
else
mapAccountBalances[""] += r.second;
}
@ -1213,7 +1213,7 @@ Value listaccounts(const Array& params, bool fHelp) @@ -1213,7 +1213,7 @@ Value listaccounts(const Array& params, bool fHelp)
}
list<CAccountingEntry> acentries;
CWalletDB().ListAccountCreditDebit("*", acentries);
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
@ -1235,11 +1235,11 @@ Value gettransaction(const Array& params, bool fHelp) @@ -1235,11 +1235,11 @@ Value gettransaction(const Array& params, bool fHelp)
hash.SetHex(params[0].get_str());
Object entry;
CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
if (!mapWallet.count(hash))
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(-5, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = mapWallet[hash];
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
int64 nCredit = wtx.GetCredit();
int64 nDebit = wtx.GetDebit();
@ -1250,10 +1250,10 @@ Value gettransaction(const Array& params, bool fHelp) @@ -1250,10 +1250,10 @@ Value gettransaction(const Array& params, bool fHelp)
if (wtx.IsFromMe())
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(mapWallet[hash], entry);
WalletTxToJSON(pwalletMain->mapWallet[hash], entry);
Array details;
ListTransactions(mapWallet[hash], "*", 0, false, details);
ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details);
entry.push_back(Pair("details", details));
}
@ -1269,7 +1269,7 @@ Value backupwallet(const Array& params, bool fHelp) @@ -1269,7 +1269,7 @@ Value backupwallet(const Array& params, bool fHelp)
"Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
string strDest = params[0].get_str();
BackupWallet(strDest);
BackupWallet(*pwalletMain, strDest);
return Value::null;
}
@ -1295,10 +1295,10 @@ Value validateaddress(const Array& params, bool fHelp) @@ -1295,10 +1295,10 @@ Value validateaddress(const Array& params, bool fHelp)
string currentAddress = Hash160ToAddress(hash160);
ret.push_back(Pair("address", currentAddress));
ret.push_back(Pair("ismine", (mapPubKeys.count(hash160) > 0)));
CRITICAL_BLOCK(cs_mapAddressBook)
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
if (mapAddressBook.count(currentAddress))
ret.push_back(Pair("account", mapAddressBook[currentAddress]));
if (pwalletMain->mapAddressBook.count(currentAddress))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[currentAddress]));
}
}
return ret;
@ -1325,7 +1325,7 @@ Value getwork(const Array& params, bool fHelp) @@ -1325,7 +1325,7 @@ Value getwork(const Array& params, bool fHelp)
static map<uint256, pair<CBlock*, unsigned int> > mapNewBlock;
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
@ -1406,7 +1406,7 @@ Value getwork(const Array& params, bool fHelp) @@ -1406,7 +1406,7 @@ Value getwork(const Array& params, bool fHelp)
pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, reservekey);
return CheckWork(pblock, *pwalletMain, reservekey);
}
}

31
src/script.cpp

@ -1021,7 +1021,7 @@ bool Solver(const CScript& scriptPubKey, vector<pair<opcodetype, valtype> >& vSo @@ -1021,7 +1021,7 @@ bool Solver(const CScript& scriptPubKey, vector<pair<opcodetype, valtype> >& vSo
}
bool Solver(const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& scriptSigRet)
bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& scriptSigRet)
{
scriptSigRet.clear();
@ -1030,7 +1030,7 @@ bool Solver(const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& s @@ -1030,7 +1030,7 @@ bool Solver(const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& s
return false;
// Compile solution
CRITICAL_BLOCK(cs_mapKeys)
CRITICAL_BLOCK(keystore.cs_mapKeys)
{
BOOST_FOREACH(PAIRTYPE(opcodetype, valtype)& item, vSolution)
{
@ -1038,12 +1038,12 @@ bool Solver(const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& s @@ -1038,12 +1038,12 @@ bool Solver(const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& s
{
// Sign
const valtype& vchPubKey = item.second;
if (!mapKeys.count(vchPubKey))
if (!keystore.HaveKey(vchPubKey))
return false;
if (hash != 0)
{
vector<unsigned char> vchSig;
if (!CKey::Sign(mapKeys[vchPubKey], hash, vchSig))
if (!CKey::Sign(keystore.GetPrivKey(vchPubKey), hash, vchSig))
return false;
vchSig.push_back((unsigned char)nHashType);
scriptSigRet << vchSig;
@ -1056,12 +1056,12 @@ bool Solver(const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& s @@ -1056,12 +1056,12 @@ bool Solver(const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& s
if (mi == mapPubKeys.end())
return false;
const vector<unsigned char>& vchPubKey = (*mi).second;
if (!mapKeys.count(vchPubKey))
if (!keystore.HaveKey(vchPubKey))
return false;
if (hash != 0)
{
vector<unsigned char> vchSig;
if (!CKey::Sign(mapKeys[vchPubKey], hash, vchSig))
if (!CKey::Sign(keystore.GetPrivKey(vchPubKey), hash, vchSig))
return false;
vchSig.push_back((unsigned char)nHashType);
scriptSigRet << vchSig << vchPubKey;
@ -1085,14 +1085,14 @@ bool IsStandard(const CScript& scriptPubKey) @@ -1085,14 +1085,14 @@ bool IsStandard(const CScript& scriptPubKey)
}
bool IsMine(const CScript& scriptPubKey)
bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
{
CScript scriptSig;
return Solver(scriptPubKey, 0, 0, scriptSig);
return Solver(keystore, scriptPubKey, 0, 0, scriptSig);
}
bool ExtractPubKey(const CScript& scriptPubKey, bool fMineOnly, vector<unsigned char>& vchPubKeyRet)
bool ExtractPubKey(const CScript& scriptPubKey, const CKeyStore* keystore, vector<unsigned char>& vchPubKeyRet)
{
vchPubKeyRet.clear();
@ -1100,7 +1100,7 @@ bool ExtractPubKey(const CScript& scriptPubKey, bool fMineOnly, vector<unsigned @@ -1100,7 +1100,7 @@ bool ExtractPubKey(const CScript& scriptPubKey, bool fMineOnly, vector<unsigned
if (!Solver(scriptPubKey, vSolution))
return false;
CRITICAL_BLOCK(cs_mapKeys)
CRITICAL_BLOCK(cs_mapPubKeys)
{
BOOST_FOREACH(PAIRTYPE(opcodetype, valtype)& item, vSolution)
{
@ -1116,7 +1116,7 @@ bool ExtractPubKey(const CScript& scriptPubKey, bool fMineOnly, vector<unsigned @@ -1116,7 +1116,7 @@ bool ExtractPubKey(const CScript& scriptPubKey, bool fMineOnly, vector<unsigned
continue;
vchPubKey = (*mi).second;
}
if (!fMineOnly || mapKeys.count(vchPubKey))
if (keystore == NULL || keystore->HaveKey(vchPubKey))
{
vchPubKeyRet = vchPubKey;
return true;
@ -1160,7 +1160,7 @@ bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const C @@ -1160,7 +1160,7 @@ bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const C
}
bool SignSignature(const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType, CScript scriptPrereq)
bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType, CScript scriptPrereq)
{
assert(nIn < txTo.vin.size());
CTxIn& txin = txTo.vin[nIn];
@ -1171,7 +1171,7 @@ bool SignSignature(const CTransaction& txFrom, CTransaction& txTo, unsigned int @@ -1171,7 +1171,7 @@ bool SignSignature(const CTransaction& txFrom, CTransaction& txTo, unsigned int
// The checksig op will also drop the signatures from its hash.
uint256 hash = SignatureHash(scriptPrereq + txout.scriptPubKey, txTo, nIn, nHashType);
if (!Solver(txout.scriptPubKey, hash, nHashType, txin.scriptSig))
if (!Solver(keystore, txout.scriptPubKey, hash, nHashType, txin.scriptSig))
return false;
txin.scriptSig = scriptPrereq + txin.scriptSig;
@ -1199,10 +1199,5 @@ bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsig @@ -1199,10 +1199,5 @@ bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsig
if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, nHashType))
return false;
// Anytime a signature is successfully verified, it's proof the outpoint is spent,
// so lets update the wallet spent flag if it doesn't know due to wallet.dat being
// restored from backup or the user making copies of wallet.dat.
WalletUpdateSpent(txin.prevout);
return true;
}

8
src/script.h

@ -5,6 +5,7 @@ @@ -5,6 +5,7 @@
#define H_BITCOIN_SCRIPT
#include "base58.h"
#include "keystore.h"
#include <string>
#include <vector>
@ -707,12 +708,11 @@ public: @@ -707,12 +708,11 @@ public:
uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
bool IsStandard(const CScript& scriptPubKey);
bool IsMine(const CScript& scriptPubKey);
bool ExtractPubKey(const CScript& scriptPubKey, bool fMineOnly, std::vector<unsigned char>& vchPubKeyRet);
bool IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
bool ExtractPubKey(const CScript& scriptPubKey, const CKeyStore* pkeystore, std::vector<unsigned char>& vchPubKeyRet);
bool ExtractHash160(const CScript& scriptPubKey, uint160& hash160Ret);
bool SignSignature(const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL, CScript scriptPrereq=CScript());
bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL, CScript scriptPrereq=CScript());
bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, int nHashType=0);
#endif

187
src/ui.cpp

@ -3,6 +3,7 @@ @@ -3,6 +3,7 @@
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "headers.h"
#include "db.h"
#include "init.h"
#include "strlcpy.h"
#include <boost/filesystem/fstream.hpp>
@ -239,7 +240,7 @@ void SetDefaultReceivingAddress(const string& strAddress) @@ -239,7 +240,7 @@ void SetDefaultReceivingAddress(const string& strAddress)
return;
if (!mapPubKeys.count(hash160))
return;
CWalletDB().WriteDefaultKey(mapPubKeys[hash160]);
CWalletDB(pwalletMain->strWalletFile).WriteDefaultKey(mapPubKeys[hash160]);
pframeMain->m_textCtrlAddress->SetValue(strAddress);
}
}
@ -289,7 +290,7 @@ CMainFrame::CMainFrame(wxWindow* parent) : CMainFrameBase(parent) @@ -289,7 +290,7 @@ CMainFrame::CMainFrame(wxWindow* parent) : CMainFrameBase(parent)
dResize = 1.22;
SetSize(dResize * GetSize().GetWidth(), 1.15 * GetSize().GetHeight());
#endif
m_staticTextBalance->SetLabel(FormatMoney(GetBalance()) + " ");
m_staticTextBalance->SetLabel(FormatMoney(pwalletMain->GetBalance()) + " ");
m_listCtrl->SetFocus();
ptaskbaricon = new CMyTaskBarIcon();
#ifdef __WXMAC_OSX__
@ -329,7 +330,7 @@ CMainFrame::CMainFrame(wxWindow* parent) : CMainFrameBase(parent) @@ -329,7 +330,7 @@ CMainFrame::CMainFrame(wxWindow* parent) : CMainFrameBase(parent)
// Fill your address text box
vector<unsigned char> vchPubKey;
if (CWalletDB("r").ReadDefaultKey(vchPubKey))
if (CWalletDB(pwalletMain->strWalletFile,"r").ReadDefaultKey(vchPubKey))
m_textCtrlAddress->SetValue(PubKeyToAddress(vchPubKey));
// Fill listctrl with wallet transactions
@ -624,7 +625,7 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex) @@ -624,7 +625,7 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)
{
int64 nUnmatured = 0;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
nUnmatured += txout.GetCredit();
nUnmatured += pwalletMain->GetCredit(txout);
if (wtx.IsInMainChain())
{
strDescription = strprintf(_("Generated (%s matures in %d more blocks)"), FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());
@ -660,19 +661,19 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex) @@ -660,19 +661,19 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)
return false;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
if (txout.IsMine())
if (pwalletMain->IsMine(txout))
{
vector<unsigned char> vchPubKey;
if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))
if (ExtractPubKey(txout.scriptPubKey, pwalletMain, vchPubKey))
{
CRITICAL_BLOCK(cs_mapAddressBook)
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
//strDescription += _("Received payment to ");
//strDescription += _("Received with address ");
strDescription += _("Received with: ");
string strAddress = PubKeyToAddress(vchPubKey);
map<string, string>::iterator mi = mapAddressBook.find(strAddress);
if (mi != mapAddressBook.end() && !(*mi).second.empty())
map<string, string>::iterator mi = pwalletMain->mapAddressBook.find(strAddress);
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
{
string strLabel = (*mi).second;
strDescription += strAddress.substr(0,12) + "... ";
@ -702,11 +703,11 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex) @@ -702,11 +703,11 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)
{
bool fAllFromMe = true;
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
fAllFromMe = fAllFromMe && txin.IsMine();
fAllFromMe = fAllFromMe && pwalletMain->IsMine(txin);
bool fAllToMe = true;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
fAllToMe = fAllToMe && txout.IsMine();
fAllToMe = fAllToMe && pwalletMain->IsMine(txout);
if (fAllFromMe && fAllToMe)
{
@ -732,7 +733,7 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex) @@ -732,7 +733,7 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)
for (int nOut = 0; nOut < wtx.vout.size(); nOut++)
{
const CTxOut& txout = wtx.vout[nOut];
if (txout.IsMine())
if (pwalletMain->IsMine(txout))
continue;
string strAddress;
@ -750,9 +751,9 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex) @@ -750,9 +751,9 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)
}
string strDescription = _("To: ");
CRITICAL_BLOCK(cs_mapAddressBook)
if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())
strDescription += mapAddressBook[strAddress] + " ";
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
if (pwalletMain->mapAddressBook.count(strAddress) && !pwalletMain->mapAddressBook[strAddress].empty())
strDescription += pwalletMain->mapAddressBook[strAddress] + " ";
strDescription += strAddress;
if (!mapValue["message"].empty())
{
@ -791,9 +792,9 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex) @@ -791,9 +792,9 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)
//
bool fAllMine = true;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
fAllMine = fAllMine && txout.IsMine();
fAllMine = fAllMine && pwalletMain->IsMine(txout);
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
fAllMine = fAllMine && txin.IsMine();
fAllMine = fAllMine && pwalletMain->IsMine(txin);
InsertLine(fNew, nIndex, hash, strSort, colour,
strStatus,
@ -820,16 +821,16 @@ void CMainFrame::OnIdle(wxIdleEvent& event) @@ -820,16 +821,16 @@ void CMainFrame::OnIdle(wxIdleEvent& event)
// Collect list of wallet transactions and sort newest first
bool fEntered = false;
vector<pair<unsigned int, uint256> > vSorted;
TRY_CRITICAL_BLOCK(cs_mapWallet)
TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
printf("RefreshListCtrl starting\n");
fEntered = true;
fRefreshListCtrl = false;
vWalletUpdated.clear();
pwalletMain->vWalletUpdated.clear();
// Do the newest transactions first
vSorted.reserve(mapWallet.size());
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
vSorted.reserve(pwalletMain->mapWallet.size());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
unsigned int nTime = UINT_MAX - wtx.GetTxTime();
@ -848,12 +849,12 @@ void CMainFrame::OnIdle(wxIdleEvent& event) @@ -848,12 +849,12 @@ void CMainFrame::OnIdle(wxIdleEvent& event)
if (fShutdown)
return;
bool fEntered = false;
TRY_CRITICAL_BLOCK(cs_mapWallet)
TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
fEntered = true;
uint256& hash = vSorted[i++].second;
map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
if (mi != mapWallet.end())
map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
if (mi != pwalletMain->mapWallet.end())
InsertTransaction((*mi).second, true);
}
if (!fEntered || i == 100 || i % 500 == 0)
@ -871,10 +872,10 @@ void CMainFrame::OnIdle(wxIdleEvent& event) @@ -871,10 +872,10 @@ void CMainFrame::OnIdle(wxIdleEvent& event)
static int64 nLastTime;
if (GetTime() > nLastTime + 30)
{
TRY_CRITICAL_BLOCK(cs_mapWallet)
TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
nLastTime = GetTime();
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
CWalletTx& wtx = (*it).second;
if (wtx.nTimeDisplayed && wtx.nTimeDisplayed != wtx.GetTxTime())
@ -895,7 +896,7 @@ void CMainFrame::RefreshStatusColumn() @@ -895,7 +896,7 @@ void CMainFrame::RefreshStatusColumn()
if (nTop == nLastTop && pindexLastBest == pindexBest)
return;
TRY_CRITICAL_BLOCK(cs_mapWallet)
TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
int nStart = nTop;
int nEnd = min(nStart + 100, m_listCtrl->GetItemCount());
@ -915,8 +916,8 @@ void CMainFrame::RefreshStatusColumn() @@ -915,8 +916,8 @@ void CMainFrame::RefreshStatusColumn()
for (int nIndex = nStart; nIndex < min(nEnd, m_listCtrl->GetItemCount()); nIndex++)
{
uint256 hash((string)GetItemText(m_listCtrl, nIndex, 1));
map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
if (mi == mapWallet.end())
map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
if (mi == pwalletMain->mapWallet.end())
{
printf("CMainFrame::RefreshStatusColumn() : tx not found in mapWallet\n");
continue;
@ -1013,41 +1014,41 @@ void CMainFrame::OnPaintListCtrl(wxPaintEvent& event) @@ -1013,41 +1014,41 @@ void CMainFrame::OnPaintListCtrl(wxPaintEvent& event)
nLastRepaintTime = GetTimeMillis();
// Update listctrl contents
if (!vWalletUpdated.empty())
if (!pwalletMain->vWalletUpdated.empty())
{
TRY_CRITICAL_BLOCK(cs_mapWallet)
TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
string strTop;
if (m_listCtrl->GetItemCount())
strTop = (string)m_listCtrl->GetItemText(0);
BOOST_FOREACH(uint256 hash, vWalletUpdated)
BOOST_FOREACH(uint256 hash, pwalletMain->vWalletUpdated)
{
map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
if (mi != mapWallet.end())
map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
if (mi != pwalletMain->mapWallet.end())
InsertTransaction((*mi).second, false);
}
vWalletUpdated.clear();
pwalletMain->vWalletUpdated.clear();
if (m_listCtrl->GetItemCount() && strTop != (string)m_listCtrl->GetItemText(0))
m_listCtrl->ScrollList(0, INT_MIN/2);
}
}
// Balance total
TRY_CRITICAL_BLOCK(cs_mapWallet)
TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
fPaintedBalance = true;
m_staticTextBalance->SetLabel(FormatMoney(GetBalance()) + " ");
m_staticTextBalance->SetLabel(FormatMoney(pwalletMain->GetBalance()) + " ");
// Count hidden and multi-line transactions
nTransactionCount = 0;
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
CWalletTx& wtx = (*it).second;
nTransactionCount += wtx.nLinesDisplayed;
}
}
}
if (!vWalletUpdated.empty() || !fPaintedBalance)
if (!pwalletMain->vWalletUpdated.empty() || !fPaintedBalance)
nNeedRepaint++;
// Update status column of visible items only
@ -1073,7 +1074,7 @@ void CMainFrame::OnPaintListCtrl(wxPaintEvent& event) @@ -1073,7 +1074,7 @@ void CMainFrame::OnPaintListCtrl(wxPaintEvent& event)
m_statusBar->SetStatusText(strStatus, 2);
// Update receiving address
string strDefaultAddress = PubKeyToAddress(vchDefaultKey);
string strDefaultAddress = PubKeyToAddress(pwalletMain->vchDefaultKey);
if (m_textCtrlAddress->GetValue() != strDefaultAddress)
m_textCtrlAddress->SetValue(strDefaultAddress);
}
@ -1182,10 +1183,10 @@ void CMainFrame::OnButtonNew(wxCommandEvent& event) @@ -1182,10 +1183,10 @@ void CMainFrame::OnButtonNew(wxCommandEvent& event)
string strName = dialog.GetValue();
// Generate new key
string strAddress = PubKeyToAddress(GetKeyFromKeyPool());
string strAddress = PubKeyToAddress(pwalletMain->GetKeyFromKeyPool());
// Save
SetAddressBookName(strAddress, strName);
pwalletMain->SetAddressBookName(strAddress, strName);
SetDefaultReceivingAddress(strAddress);
}
@ -1203,10 +1204,10 @@ void CMainFrame::OnListItemActivated(wxListEvent& event) @@ -1203,10 +1204,10 @@ void CMainFrame::OnListItemActivated(wxListEvent& event)
{
uint256 hash((string)GetItemText(m_listCtrl, event.GetIndex(), 1));
CWalletTx wtx;
CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
if (mi == mapWallet.end())
map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
if (mi == pwalletMain->mapWallet.end())
{
printf("CMainFrame::OnListItemActivated() : tx not found in mapWallet\n");
return;
@ -1234,7 +1235,7 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails @@ -1234,7 +1235,7 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails
#ifdef __WXMSW__
SetSize(nScaleX * GetSize().GetWidth(), nScaleY * GetSize().GetHeight());
#endif
CRITICAL_BLOCK(cs_mapAddressBook)
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
string strHTML;
strHTML.reserve(4000);
@ -1284,19 +1285,19 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails @@ -1284,19 +1285,19 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails
// Credit
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
if (txout.IsMine())
if (pwalletMain->IsMine(txout))
{
vector<unsigned char> vchPubKey;
if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))
if (ExtractPubKey(txout.scriptPubKey, pwalletMain, vchPubKey))
{
string strAddress = PubKeyToAddress(vchPubKey);
if (mapAddressBook.count(strAddress))
if (pwalletMain->mapAddressBook.count(strAddress))
{
strHTML += string() + _("<b>From:</b> ") + _("unknown") + "<br>";
strHTML += _("<b>To:</b> ");
strHTML += HtmlEscape(strAddress);
if (!mapAddressBook[strAddress].empty())
strHTML += _(" (yours, label: ") + mapAddressBook[strAddress] + ")";
if (!pwalletMain->mapAddressBook[strAddress].empty())
strHTML += _(" (yours, label: ") + pwalletMain->mapAddressBook[strAddress] + ")";
else
strHTML += _(" (yours)");
strHTML += "<br>";
@ -1318,8 +1319,8 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails @@ -1318,8 +1319,8 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails
// Online transaction
strAddress = wtx.mapValue["to"];
strHTML += _("<b>To:</b> ");
if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())
strHTML += mapAddressBook[strAddress] + " ";
if (pwalletMain->mapAddressBook.count(strAddress) && !pwalletMain->mapAddressBook[strAddress].empty())
strHTML += pwalletMain->mapAddressBook[strAddress] + " ";
strHTML += HtmlEscape(strAddress) + "<br>";
}
@ -1334,7 +1335,7 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails @@ -1334,7 +1335,7 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails
//
int64 nUnmatured = 0;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
nUnmatured += txout.GetCredit();
nUnmatured += pwalletMain->GetCredit(txout);
strHTML += _("<b>Credit:</b> ");
if (wtx.IsInMainChain())
strHTML += strprintf(_("(%s matures in %d more blocks)"), FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());
@ -1353,11 +1354,11 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails @@ -1353,11 +1354,11 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails
{
bool fAllFromMe = true;
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
fAllFromMe = fAllFromMe && txin.IsMine();
fAllFromMe = fAllFromMe && pwalletMain->IsMine(txin);
bool fAllToMe = true;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
fAllToMe = fAllToMe && txout.IsMine();
fAllToMe = fAllToMe && pwalletMain->IsMine(txout);
if (fAllFromMe)
{
@ -1366,7 +1367,7 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails @@ -1366,7 +1367,7 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails
//
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
if (txout.IsMine())
if (pwalletMain->IsMine(txout))
continue;
if (wtx.mapValue["to"].empty())
@ -1377,8 +1378,8 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails @@ -1377,8 +1378,8 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails
{
string strAddress = Hash160ToAddress(hash160);
strHTML += _("<b>To:</b> ");
if (mapAddressBook.count(strAddress) && !mapAddressBook[strAddress].empty())
strHTML += mapAddressBook[strAddress] + " ";
if (pwalletMain->mapAddressBook.count(strAddress) && !pwalletMain->mapAddressBook[strAddress].empty())
strHTML += pwalletMain->mapAddressBook[strAddress] + " ";
strHTML += strAddress;
strHTML += "<br>";
}
@ -1406,11 +1407,11 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails @@ -1406,11 +1407,11 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails
// Mixed debit transaction
//
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
if (txin.IsMine())
strHTML += _("<b>Debit:</b> ") + FormatMoney(-txin.GetDebit()) + "<br>";
if (pwalletMain->IsMine(txin))
strHTML += _("<b>Debit:</b> ") + FormatMoney(-pwalletMain->GetDebit(txin)) + "<br>";
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.IsMine())
strHTML += _("<b>Credit:</b> ") + FormatMoney(txout.GetCredit()) + "<br>";
if (pwalletMain->IsMine(txout))
strHTML += _("<b>Credit:</b> ") + FormatMoney(pwalletMain->GetCredit(txout)) + "<br>";
}
}
@ -1436,30 +1437,30 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails @@ -1436,30 +1437,30 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails
{
strHTML += "<hr><br>debug print<br><br>";
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
if (txin.IsMine())
strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>";
if (pwalletMain->IsMine(txin))
strHTML += "<b>Debit:</b> " + FormatMoney(-pwalletMain->GetDebit(txin)) + "<br>";
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.IsMine())
strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";
if (pwalletMain->IsMine(txout))
strHTML += "<b>Credit:</b> " + FormatMoney(pwalletMain->GetCredit(txout)) + "<br>";
strHTML += "<br><b>Transaction:</b><br>";
strHTML += HtmlEscape(wtx.ToString(), true);
strHTML += "<br><b>Inputs:</b><br>";
CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
COutPoint prevout = txin.prevout;
map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
if (mi != mapWallet.end())
map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(prevout.hash);
if (mi != pwalletMain->mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (prevout.n < prev.vout.size())
{
strHTML += HtmlEscape(prev.ToString(), true);
strHTML += " &nbsp;&nbsp; " + FormatTxStatus(prev) + ", ";
strHTML = strHTML + "IsMine=" + (prev.vout[prevout.n].IsMine() ? "true" : "false") + "<br>";
strHTML = strHTML + "IsMine=" + (pwalletMain->IsMine(prev.vout[prevout.n]) ? "true" : "false") + "<br>";
}
}
}
@ -1750,7 +1751,7 @@ void COptionsDialog::OnButtonCancel(wxCommandEvent& event) @@ -1750,7 +1751,7 @@ void COptionsDialog::OnButtonCancel(wxCommandEvent& event)
void COptionsDialog::OnButtonApply(wxCommandEvent& event)
{
CWalletDB walletdb;
CWalletDB walletdb(pwalletMain->strWalletFile);
int64 nPrevTransactionFee = nTransactionFee;
if (ParseMoney(m_textCtrlTransactionFee->GetValue(), nTransactionFee) && nTransactionFee != nPrevTransactionFee)
@ -1927,12 +1928,12 @@ void CSendDialog::OnButtonSend(wxCommandEvent& event) @@ -1927,12 +1928,12 @@ void CSendDialog::OnButtonSend(wxCommandEvent& event)
wxMessageBox(_("Error in amount "), _("Send Coins"));
return;
}
if (nValue > GetBalance())
if (nValue > pwalletMain->GetBalance())
{
wxMessageBox(_("Amount exceeds your balance "), _("Send Coins"));
return;
}
if (nValue + nTransactionFee > GetBalance())
if (nValue + nTransactionFee > pwalletMain->GetBalance())
{
wxMessageBox(string(_("Total exceeds your balance when the ")) + FormatMoney(nTransactionFee) + _(" transaction fee is included "), _("Send Coins"));
return;
@ -1950,7 +1951,7 @@ void CSendDialog::OnButtonSend(wxCommandEvent& event) @@ -1950,7 +1951,7 @@ void CSendDialog::OnButtonSend(wxCommandEvent& event)
CScript scriptPubKey;
scriptPubKey << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;
string strError = SendMoney(scriptPubKey, nValue, wtx, true);
string strError = pwalletMain->SendMoney(scriptPubKey, nValue, wtx, true);
if (strError == "")
wxMessageBox(_("Payment sent "), _("Sending..."));
else if (strError == "ABORTED")
@ -1982,9 +1983,9 @@ void CSendDialog::OnButtonSend(wxCommandEvent& event) @@ -1982,9 +1983,9 @@ void CSendDialog::OnButtonSend(wxCommandEvent& event)
return;
}
CRITICAL_BLOCK(cs_mapAddressBook)
if (!mapAddressBook.count(strAddress))
SetAddressBookName(strAddress, "");
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
if (!pwalletMain->mapAddressBook.count(strAddress))
pwalletMain->SetAddressBookName(strAddress, "");
EndModal(true);
}
@ -2168,7 +2169,7 @@ void SendingDialogStartTransfer(void* parg) @@ -2168,7 +2169,7 @@ void SendingDialogStartTransfer(void* parg)
void CSendingDialog::StartTransfer()
{
// Make sure we have enough money
if (nPrice + nTransactionFee > GetBalance())
if (nPrice + nTransactionFee > pwalletMain->GetBalance())
{
Error(_("Insufficient funds"));
return;
@ -2239,16 +2240,16 @@ void CSendingDialog::OnReply2(CDataStream& vRecv) @@ -2239,16 +2240,16 @@ void CSendingDialog::OnReply2(CDataStream& vRecv)
// Pay
if (!Status(_("Creating transaction...")))
return;
if (nPrice + nTransactionFee > GetBalance())
if (nPrice + nTransactionFee > pwalletMain->GetBalance())
{
Error(_("Insufficient funds"));
return;
}
CReserveKey reservekey;
CReserveKey reservekey(pwalletMain);
int64 nFeeRequired;
if (!CreateTransaction(scriptPubKey, nPrice, wtx, reservekey, nFeeRequired))
if (!pwalletMain->CreateTransaction(scriptPubKey, nPrice, wtx, reservekey, nFeeRequired))
{
if (nPrice + nFeeRequired > GetBalance())
if (nPrice + nFeeRequired > pwalletMain->GetBalance())
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()));
else
Error(_("Transaction creation failed"));
@ -2286,7 +2287,7 @@ void CSendingDialog::OnReply2(CDataStream& vRecv) @@ -2286,7 +2287,7 @@ void CSendingDialog::OnReply2(CDataStream& vRecv)
return;
// Commit
if (!CommitTransaction(wtx, reservekey))
if (!pwalletMain->CommitTransaction(wtx, reservekey))
{
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."));
return;
@ -2380,11 +2381,11 @@ CAddressBookDialog::CAddressBookDialog(wxWindow* parent, const wxString& strInit @@ -2380,11 +2381,11 @@ CAddressBookDialog::CAddressBookDialog(wxWindow* parent, const wxString& strInit
m_listCtrlReceiving->SetFocus();
// Fill listctrl with address book data
CRITICAL_BLOCK(cs_mapKeys)
CRITICAL_BLOCK(cs_mapAddressBook)
CRITICAL_BLOCK(pwalletMain->cs_mapKeys)
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
string strDefaultReceiving = (string)pframeMain->m_textCtrlAddress->GetValue();
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
BOOST_FOREACH(const PAIRTYPE(string, string)& item, pwalletMain->mapAddressBook)
{
string strAddress = item.first;
string strName = item.second;
@ -2443,7 +2444,7 @@ void CAddressBookDialog::OnListEndLabelEdit(wxListEvent& event) @@ -2443,7 +2444,7 @@ void CAddressBookDialog::OnListEndLabelEdit(wxListEvent& event)
if (event.IsEditCancelled())
return;
string strAddress = (string)GetItemText(m_listCtrl, event.GetIndex(), 1);
SetAddressBookName(strAddress, string(event.GetText()));
pwalletMain->SetAddressBookName(strAddress, string(event.GetText()));
pframeMain->RefreshListCtrl();
}
@ -2478,7 +2479,7 @@ void CAddressBookDialog::OnButtonDelete(wxCommandEvent& event) @@ -2478,7 +2479,7 @@ void CAddressBookDialog::OnButtonDelete(wxCommandEvent& event)
if (m_listCtrl->GetItemState(nIndex, wxLIST_STATE_SELECTED))
{
string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);
CWalletDB().EraseName(strAddress);
CWalletDB(pwalletMain->strWalletFile).EraseName(strAddress);
m_listCtrl->DeleteItem(nIndex);
}
}
@ -2538,8 +2539,8 @@ void CAddressBookDialog::OnButtonEdit(wxCommandEvent& event) @@ -2538,8 +2539,8 @@ void CAddressBookDialog::OnButtonEdit(wxCommandEvent& event)
// Write back
if (strAddress != strAddressOrg)
CWalletDB().EraseName(strAddressOrg);
SetAddressBookName(strAddress, strName);
CWalletDB(pwalletMain->strWalletFile).EraseName(strAddressOrg);
pwalletMain->SetAddressBookName(strAddress, strName);
m_listCtrl->SetItem(nIndex, 1, strAddress);
m_listCtrl->SetItemText(nIndex, strName);
pframeMain->RefreshListCtrl();
@ -2575,11 +2576,11 @@ void CAddressBookDialog::OnButtonNew(wxCommandEvent& event) @@ -2575,11 +2576,11 @@ void CAddressBookDialog::OnButtonNew(wxCommandEvent& event)
strName = dialog.GetValue();
// Generate new key
strAddress = PubKeyToAddress(GetKeyFromKeyPool());
strAddress = PubKeyToAddress(pwalletMain->GetKeyFromKeyPool());
}
// Add to list and select it
SetAddressBookName(strAddress, strName);
pwalletMain->SetAddressBookName(strAddress, strName);
int nIndex = InsertLine(m_listCtrl, strName, strAddress);
SetSelection(m_listCtrl, nIndex);
m_listCtrl->SetFocus();

3
src/ui.h

@ -4,6 +4,9 @@ @@ -4,6 +4,9 @@
#ifndef BITCOIN_UI_H
#define BITCOIN_UI_H
#include <boost/function.hpp>
#include "wallet.h"
DECLARE_EVENT_TYPE(wxEVT_UITHREADCALL, -1)

1123
src/wallet.cpp

File diff suppressed because it is too large Load Diff

615
src/wallet.h

@ -0,0 +1,615 @@ @@ -0,0 +1,615 @@
// Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_WALLET_H
#define BITCOIN_WALLET_H
#include "bignum.h"
#include "key.h"
#include "script.h"
class CWalletTx;
class CReserveKey;
class CWalletDB;
class CWallet : public CKeyStore
{
private:
bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
public:
bool fFileBacked;
std::string strWalletFile;
std::set<int64> setKeyPool;
CCriticalSection cs_setKeyPool;
CWallet()
{
fFileBacked = false;
}
CWallet(std::string strWalletFileIn)
{
strWalletFile = strWalletFileIn;
fFileBacked = true;
}
mutable CCriticalSection cs_mapWallet;
std::map<uint256, CWalletTx> mapWallet;
std::vector<uint256> vWalletUpdated;
std::map<uint256, int> mapRequestCount;
mutable CCriticalSection cs_mapRequestCount;
std::map<std::string, std::string> mapAddressBook;
mutable CCriticalSection cs_mapAddressBook;
std::vector<unsigned char> vchDefaultKey;
CKey keyUser;
bool AddKey(const CKey& key);
bool AddToWallet(const CWalletTx& wtxIn);
bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
bool EraseFromWallet(uint256 hash);
void WalletUpdateSpent(const CTransaction& prevout);
int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
void ReacceptWalletTransactions();
void ResendWalletTransactions();
int64 GetBalance() const;
bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
bool BroadcastTransaction(CWalletTx& wtxNew);
std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
std::string SendMoneyToBitcoinAddress(std::string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
void KeepKey(int64 nIndex);
void ReturnKey(int64 nIndex);
std::vector<unsigned char> GetKeyFromKeyPool();
int64 GetOldestKeyPoolTime();
bool IsMine(const CTxIn& txin) const;
int64 GetDebit(const CTxIn& txin) const;
bool IsMine(const CTxOut& txout) const
{
return ::IsMine(*this, txout.scriptPubKey);
}
int64 GetCredit(const CTxOut& txout) const
{
if (!MoneyRange(txout.nValue))
throw std::runtime_error("CWallet::GetCredit() : value out of range");
return (IsMine(txout) ? txout.nValue : 0);
}
bool IsChange(const CTxOut& txout) const
{
std::vector<unsigned char> vchPubKey;
if (ExtractPubKey(txout.scriptPubKey, this, vchPubKey))
CRITICAL_BLOCK(cs_mapAddressBook)
if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
return true;
return false;
}
int64 GetChange(const CTxOut& txout) const
{
if (!MoneyRange(txout.nValue))
throw std::runtime_error("CWallet::GetChange() : value out of range");
if (IsChange(txout) ? txout.nValue : 0);
}
bool IsMine(const CTransaction& tx) const
{
BOOST_FOREACH(const CTxOut& txout, tx.vout)
if (IsMine(txout))
return true;
return false;
}
bool IsFromMe(const CTransaction& tx) const
{
return (GetDebit(tx) > 0);
}
int64 GetDebit(const CTransaction& tx) const
{
int64 nDebit = 0;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
nDebit += GetDebit(txin);
if (!MoneyRange(nDebit))
throw std::runtime_error("CWallet::GetDebit() : value out of range");
}
return nDebit;
}
int64 GetCredit(const CTransaction& tx) const
{
int64 nCredit = 0;
BOOST_FOREACH(const CTxOut& txout, tx.vout)
{
nCredit += GetCredit(txout);
if (!MoneyRange(nCredit))
throw std::runtime_error("CWallet::GetCredit() : value out of range");
}
return nCredit;
}
int64 GetChange(const CTransaction& tx) const
{
int64 nChange = 0;
BOOST_FOREACH(const CTxOut& txout, tx.vout)
{
nChange += GetChange(txout);
if (!MoneyRange(nChange))
throw std::runtime_error("CWallet::GetChange() : value out of range");
}
return nChange;
}
void SetBestChain(const CBlockLocator& loc)
{
CWalletDB walletdb(strWalletFile);
walletdb.WriteBestBlock(loc);
}
bool LoadWallet(bool& fFirstRunRet);
// bool BackupWallet(const std::string& strDest);
bool SetAddressBookName(const std::string& strAddress, const std::string& strName)
{
if (!fFileBacked)
return false;
return CWalletDB(strWalletFile).WriteName(strAddress, strName);
}
void UpdatedTransaction(const uint256 &hashTx)
{
CRITICAL_BLOCK(cs_mapWallet)
vWalletUpdated.push_back(hashTx);
}
void PrintWallet(const CBlock& block);
void Inventory(const uint256 &hash)
{
CRITICAL_BLOCK(cs_mapRequestCount)
{
std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
if (mi != mapRequestCount.end())
(*mi).second++;
}
}
bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
};
class CReserveKey
{
protected:
CWallet* pwallet;
int64 nIndex;
std::vector<unsigned char> vchPubKey;
public:
CReserveKey(CWallet* pwalletIn)
{
nIndex = -1;
pwallet = pwalletIn;
}
~CReserveKey()
{
if (!fShutdown)
ReturnKey();
}
void ReturnKey();
std::vector<unsigned char> GetReservedKey();
void KeepKey();
};
//
// A transaction with a bunch of additional info that only the owner cares
// about. It includes any unrecorded transactions needed to link it back
// to the block chain.
//
class CWalletTx : public CMerkleTx
{
public:
const CWallet* pwallet;
std::vector<CMerkleTx> vtxPrev;
std::map<std::string, std::string> mapValue;
std::vector<std::pair<std::string, std::string> > vOrderForm;
unsigned int fTimeReceivedIsTxTime;
unsigned int nTimeReceived; // time received by this node
char fFromMe;
std::string strFromAccount;
std::vector<char> vfSpent;
// memory only
mutable char fDebitCached;
mutable char fCreditCached;
mutable char fAvailableCreditCached;
mutable char fChangeCached;
mutable int64 nDebitCached;
mutable int64 nCreditCached;
mutable int64 nAvailableCreditCached;
mutable int64 nChangeCached;
// memory only UI hints
mutable unsigned int nTimeDisplayed;
mutable int nLinesDisplayed;
mutable char fConfirmedDisplayed;
CWalletTx()
{
Init(NULL);
}
CWalletTx(const CWallet* pwalletIn)
{
Init(pwalletIn);
}
CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
{
Init(pwalletIn);
}
CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
{
Init(pwalletIn);
}
void Init(const CWallet* pwalletIn)
{
pwallet = pwalletIn;
vtxPrev.clear();
mapValue.clear();
vOrderForm.clear();
fTimeReceivedIsTxTime = false;
nTimeReceived = 0;
fFromMe = false;
strFromAccount.clear();
vfSpent.clear();
fDebitCached = false;
fCreditCached = false;
fAvailableCreditCached = false;
fChangeCached = false;
nDebitCached = 0;
nCreditCached = 0;
nAvailableCreditCached = 0;
nChangeCached = 0;
nTimeDisplayed = 0;
nLinesDisplayed = 0;
fConfirmedDisplayed = false;
}
IMPLEMENT_SERIALIZE
(
CWalletTx* pthis = const_cast<CWalletTx*>(this);
if (fRead)
pthis->Init(NULL);
char fSpent = false;
if (!fRead)
{
pthis->mapValue["fromaccount"] = pthis->strFromAccount;
std::string str;
BOOST_FOREACH(char f, vfSpent)
{
str += (f ? '1' : '0');
if (f)
fSpent = true;
}
pthis->mapValue["spent"] = str;
}
nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
READWRITE(vtxPrev);
READWRITE(mapValue);
READWRITE(vOrderForm);
READWRITE(fTimeReceivedIsTxTime);
READWRITE(nTimeReceived);
READWRITE(fFromMe);
READWRITE(fSpent);
if (fRead)
{
pthis->strFromAccount = pthis->mapValue["fromaccount"];
if (mapValue.count("spent"))
BOOST_FOREACH(char c, pthis->mapValue["spent"])
pthis->vfSpent.push_back(c != '0');
else
pthis->vfSpent.assign(vout.size(), fSpent);
}
pthis->mapValue.erase("fromaccount");
pthis->mapValue.erase("version");
pthis->mapValue.erase("spent");
)
// marks certain txout's as spent
// returns true if any update took place
bool UpdateSpent(const std::vector<char>& vfNewSpent)
{
bool fReturn = false;
for (int i=0; i < vfNewSpent.size(); i++)
{
if (i == vfSpent.size())
break;
if (vfNewSpent[i] && !vfSpent[i])
{
vfSpent[i] = true;
fReturn = true;
fAvailableCreditCached = false;
}
}
return fReturn;
}
void MarkDirty()
{
fCreditCached = false;
fAvailableCreditCached = false;
fDebitCached = false;
fChangeCached = false;
}
void MarkSpent(unsigned int nOut)
{
if (nOut >= vout.size())
throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
vfSpent.resize(vout.size());
if (!vfSpent[nOut])
{
vfSpent[nOut] = true;
fAvailableCreditCached = false;
}
}
bool IsSpent(unsigned int nOut) const
{
if (nOut >= vout.size())
throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
if (nOut >= vfSpent.size())
return false;
return (!!vfSpent[nOut]);
}
int64 GetDebit() const
{
if (vin.empty())
return 0;
if (fDebitCached)
return nDebitCached;
nDebitCached = pwallet->GetDebit(*this);
fDebitCached = true;
return nDebitCached;
}
int64 GetCredit(bool fUseCache=true) const
{
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
// GetBalance can assume transactions in mapWallet won't change
if (fUseCache && fCreditCached)
return nCreditCached;
nCreditCached = pwallet->GetCredit(*this);
fCreditCached = true;
return nCreditCached;
}
int64 GetAvailableCredit(bool fUseCache=true) const
{
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
if (fUseCache && fAvailableCreditCached)
return nAvailableCreditCached;
int64 nCredit = 0;
for (int i = 0; i < vout.size(); i++)
{
if (!IsSpent(i))
{
const CTxOut &txout = vout[i];
nCredit += pwallet->GetCredit(txout);
if (!MoneyRange(nCredit))
throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
}
}
nAvailableCreditCached = nCredit;
fAvailableCreditCached = true;
return nCredit;
}
int64 GetChange() const
{
if (fChangeCached)
return nChangeCached;
nChangeCached = pwallet->GetChange(*this);
fChangeCached = true;
return nChangeCached;
}
void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
int64& nSent, int64& nFee) const;
bool IsFromMe() const
{
return (GetDebit() > 0);
}
bool IsConfirmed() const
{
// Quick answer in most cases
if (!IsFinal())
return false;
if (GetDepthInMainChain() >= 1)
return true;
if (!IsFromMe()) // using wtx's cached debit
return false;
// If no confirmations but it's from us, we can still
// consider it confirmed if all dependencies are confirmed
std::map<uint256, const CMerkleTx*> mapPrev;
std::vector<const CMerkleTx*> vWorkQueue;
vWorkQueue.reserve(vtxPrev.size()+1);
vWorkQueue.push_back(this);
for (int i = 0; i < vWorkQueue.size(); i++)
{
const CMerkleTx* ptx = vWorkQueue[i];
if (!ptx->IsFinal())
return false;
if (ptx->GetDepthInMainChain() >= 1)
continue;
if (!pwallet->IsFromMe(*ptx))
return false;
if (mapPrev.empty())
BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
mapPrev[tx.GetHash()] = &tx;
BOOST_FOREACH(const CTxIn& txin, ptx->vin)
{
if (!mapPrev.count(txin.prevout.hash))
return false;
vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
}
}
return true;
}
bool WriteToDisk();
int64 GetTxTime() const;
int GetRequestCount() const;
void AddSupportingTransactions(CTxDB& txdb);
bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
bool AcceptWalletTransaction();
void RelayWalletTransaction(CTxDB& txdb);
void RelayWalletTransaction();
};
//
// Private key that includes an expiration date in case it never gets used.
//
class CWalletKey
{
public:
CPrivKey vchPrivKey;
int64 nTimeCreated;
int64 nTimeExpires;
std::string strComment;
//// todo: add something to note what created it (user, getnewaddress, change)
//// maybe should have a map<string, string> property map
CWalletKey(int64 nExpires=0)
{
nTimeCreated = (nExpires ? GetTime() : 0);
nTimeExpires = nExpires;
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vchPrivKey);
READWRITE(nTimeCreated);
READWRITE(nTimeExpires);
READWRITE(strComment);
)
};
//
// Account information.
// Stored in wallet with key "acc"+string account name
//
class CAccount
{
public:
std::vector<unsigned char> vchPubKey;
CAccount()
{
SetNull();
}
void SetNull()
{
vchPubKey.clear();
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vchPubKey);
)
};
//
// Internal transfers.
// Database key is acentry<account><counter>
//
class CAccountingEntry
{
public:
std::string strAccount;
int64 nCreditDebit;
int64 nTime;
std::string strOtherAccount;
std::string strComment;
CAccountingEntry()
{
SetNull();
}
void SetNull()
{
nCreditDebit = 0;
nTime = 0;
strAccount.clear();
strOtherAccount.clear();
strComment.clear();
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
// Note: strAccount is serialized as part of the key, not here.
READWRITE(nCreditDebit);
READWRITE(nTime);
READWRITE(strOtherAccount);
READWRITE(strComment);
)
};
bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
#endif
Loading…
Cancel
Save