make bitcoin include files more modular

This commit is contained in:
Wladimir J. van der Laan 2011-05-15 09:11:04 +02:00 committed by Witchspace
parent c22feee634
commit 223b6f1ba4
25 changed files with 640 additions and 510 deletions

View file

@ -11,12 +11,17 @@
// - E-mail usually won't line-break if there's no punctuation to break at. // - E-mail usually won't line-break if there's no punctuation to break at.
// - Doubleclicking selects the whole number as one word if it's all alphanumeric. // - Doubleclicking selects the whole number as one word if it's all alphanumeric.
// //
#ifndef BITCOIN_BASE58_H
#define BITCOIN_BASE58_H
#include <string>
#include <vector>
#include "bignum.h"
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
inline string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend) inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{ {
CAutoBN_CTX pctx; CAutoBN_CTX pctx;
CBigNum bn58 = 58; CBigNum bn58 = 58;
@ -24,15 +29,15 @@ inline string EncodeBase58(const unsigned char* pbegin, const unsigned char* pen
// Convert big endian data to little endian // Convert big endian data to little endian
// Extra zero at the end make sure bignum will interpret as a positive number // Extra zero at the end make sure bignum will interpret as a positive number
vector<unsigned char> vchTmp(pend-pbegin+1, 0); std::vector<unsigned char> vchTmp(pend-pbegin+1, 0);
reverse_copy(pbegin, pend, vchTmp.begin()); reverse_copy(pbegin, pend, vchTmp.begin());
// Convert little endian data to bignum // Convert little endian data to bignum
CBigNum bn; CBigNum bn;
bn.setvch(vchTmp); bn.setvch(vchTmp);
// Convert bignum to string // Convert bignum to std::string
string str; std::string str;
str.reserve((pend - pbegin) * 138 / 100 + 1); str.reserve((pend - pbegin) * 138 / 100 + 1);
CBigNum dv; CBigNum dv;
CBigNum rem; CBigNum rem;
@ -49,17 +54,17 @@ inline string EncodeBase58(const unsigned char* pbegin, const unsigned char* pen
for (const unsigned char* p = pbegin; p < pend && *p == 0; p++) for (const unsigned char* p = pbegin; p < pend && *p == 0; p++)
str += pszBase58[0]; str += pszBase58[0];
// Convert little endian string to big endian // Convert little endian std::string to big endian
reverse(str.begin(), str.end()); reverse(str.begin(), str.end());
return str; return str;
} }
inline string EncodeBase58(const vector<unsigned char>& vch) inline std::string EncodeBase58(const std::vector<unsigned char>& vch)
{ {
return EncodeBase58(&vch[0], &vch[0] + vch.size()); return EncodeBase58(&vch[0], &vch[0] + vch.size());
} }
inline bool DecodeBase58(const char* psz, vector<unsigned char>& vchRet) inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet)
{ {
CAutoBN_CTX pctx; CAutoBN_CTX pctx;
vchRet.clear(); vchRet.clear();
@ -88,7 +93,7 @@ inline bool DecodeBase58(const char* psz, vector<unsigned char>& vchRet)
} }
// Get bignum as little endian data // Get bignum as little endian data
vector<unsigned char> vchTmp = bn.getvch(); std::vector<unsigned char> vchTmp = bn.getvch();
// Trim off sign byte if present // Trim off sign byte if present
if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80) if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80)
@ -105,7 +110,7 @@ inline bool DecodeBase58(const char* psz, vector<unsigned char>& vchRet)
return true; return true;
} }
inline bool DecodeBase58(const string& str, vector<unsigned char>& vchRet) inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{ {
return DecodeBase58(str.c_str(), vchRet); return DecodeBase58(str.c_str(), vchRet);
} }
@ -114,16 +119,16 @@ inline bool DecodeBase58(const string& str, vector<unsigned char>& vchRet)
inline string EncodeBase58Check(const vector<unsigned char>& vchIn) inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{ {
// add 4-byte hash check to the end // add 4-byte hash check to the end
vector<unsigned char> vch(vchIn); std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end()); uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4); vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch); return EncodeBase58(vch);
} }
inline bool DecodeBase58Check(const char* psz, vector<unsigned char>& vchRet) inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{ {
if (!DecodeBase58(psz, vchRet)) if (!DecodeBase58(psz, vchRet))
return false; return false;
@ -142,7 +147,7 @@ inline bool DecodeBase58Check(const char* psz, vector<unsigned char>& vchRet)
return true; return true;
} }
inline bool DecodeBase58Check(const string& str, vector<unsigned char>& vchRet) inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{ {
return DecodeBase58Check(str.c_str(), vchRet); return DecodeBase58Check(str.c_str(), vchRet);
} }
@ -154,17 +159,17 @@ inline bool DecodeBase58Check(const string& str, vector<unsigned char>& vchRet)
#define ADDRESSVERSION ((unsigned char)(fTestNet ? 111 : 0)) #define ADDRESSVERSION ((unsigned char)(fTestNet ? 111 : 0))
inline string Hash160ToAddress(uint160 hash160) inline std::string Hash160ToAddress(uint160 hash160)
{ {
// add 1-byte version number to the front // add 1-byte version number to the front
vector<unsigned char> vch(1, ADDRESSVERSION); std::vector<unsigned char> vch(1, ADDRESSVERSION);
vch.insert(vch.end(), UBEGIN(hash160), UEND(hash160)); vch.insert(vch.end(), UBEGIN(hash160), UEND(hash160));
return EncodeBase58Check(vch); return EncodeBase58Check(vch);
} }
inline bool AddressToHash160(const char* psz, uint160& hash160Ret) inline bool AddressToHash160(const char* psz, uint160& hash160Ret)
{ {
vector<unsigned char> vch; std::vector<unsigned char> vch;
if (!DecodeBase58Check(psz, vch)) if (!DecodeBase58Check(psz, vch))
return false; return false;
if (vch.empty()) if (vch.empty())
@ -176,7 +181,7 @@ inline bool AddressToHash160(const char* psz, uint160& hash160Ret)
return (nVersion <= ADDRESSVERSION); return (nVersion <= ADDRESSVERSION);
} }
inline bool AddressToHash160(const string& str, uint160& hash160Ret) inline bool AddressToHash160(const std::string& str, uint160& hash160Ret)
{ {
return AddressToHash160(str.c_str(), hash160Ret); return AddressToHash160(str.c_str(), hash160Ret);
} }
@ -187,7 +192,7 @@ inline bool IsValidBitcoinAddress(const char* psz)
return AddressToHash160(psz, hash160); return AddressToHash160(psz, hash160);
} }
inline bool IsValidBitcoinAddress(const string& str) inline bool IsValidBitcoinAddress(const std::string& str)
{ {
return IsValidBitcoinAddress(str.c_str()); return IsValidBitcoinAddress(str.c_str());
} }
@ -195,7 +200,9 @@ inline bool IsValidBitcoinAddress(const string& str)
inline string PubKeyToAddress(const vector<unsigned char>& vchPubKey) inline std::string PubKeyToAddress(const std::vector<unsigned char>& vchPubKey)
{ {
return Hash160ToAddress(Hash160(vchPubKey)); return Hash160ToAddress(Hash160(vchPubKey));
} }
#endif

View file

@ -1,14 +1,14 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying // Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_BIGNUM_H
#define BITCOIN_BIGNUM_H
#include <stdexcept> #include <stdexcept>
#include <vector> #include <vector>
#include <openssl/bn.h> #include <openssl/bn.h>
#include "util.h"
class bignum_error : public std::runtime_error class bignum_error : public std::runtime_error
{ {
@ -308,7 +308,7 @@ public:
CAutoBN_CTX pctx; CAutoBN_CTX pctx;
CBigNum bnBase = nBase; CBigNum bnBase = nBase;
CBigNum bn0 = 0; CBigNum bn0 = 0;
string str; std::string str;
CBigNum bn = *this; CBigNum bn = *this;
BN_set_negative(&bn, false); BN_set_negative(&bn, false);
CBigNum dv; CBigNum dv;
@ -348,7 +348,7 @@ public:
template<typename Stream> template<typename Stream>
void Unserialize(Stream& s, int nType=0, int nVersion=VERSION) void Unserialize(Stream& s, int nType=0, int nVersion=VERSION)
{ {
vector<unsigned char> vch; std::vector<unsigned char> vch;
::Unserialize(s, vch, nType, nVersion); ::Unserialize(s, vch, nType, nVersion);
setvch(vch); setvch(vch);
} }
@ -530,3 +530,5 @@ inline bool operator<=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a,
inline bool operator>=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) >= 0); } inline bool operator>=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) >= 0); }
inline bool operator<(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) < 0); } inline bool operator<(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) < 0); }
inline bool operator>(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) > 0); } inline bool operator>(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) > 0); }
#endif

View file

@ -4,6 +4,9 @@
#include "headers.h" #include "headers.h"
using namespace std;
using namespace boost;
void ThreadFlushWalletDB(void* parg); void ThreadFlushWalletDB(void* parg);
@ -434,13 +437,13 @@ bool CTxDB::LoadBlockIndex()
// Calculate bnChainWork // Calculate bnChainWork
vector<pair<int, CBlockIndex*> > vSortedByHeight; vector<pair<int, CBlockIndex*> > vSortedByHeight;
vSortedByHeight.reserve(mapBlockIndex.size()); vSortedByHeight.reserve(mapBlockIndex.size());
foreach(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex) BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
{ {
CBlockIndex* pindex = item.second; CBlockIndex* pindex = item.second;
vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex)); vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
} }
sort(vSortedByHeight.begin(), vSortedByHeight.end()); sort(vSortedByHeight.begin(), vSortedByHeight.end());
foreach(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight) BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
{ {
CBlockIndex* pindex = item.second; CBlockIndex* pindex = item.second;
pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork(); pindex->bnChainWork = (pindex->pprev ? pindex->pprev->bnChainWork : 0) + pindex->GetBlockWork();
@ -603,7 +606,7 @@ int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
ListAccountCreditDebit(strAccount, entries); ListAccountCreditDebit(strAccount, entries);
int64 nCreditDebit = 0; int64 nCreditDebit = 0;
foreach (const CAccountingEntry& entry, entries) BOOST_FOREACH (const CAccountingEntry& entry, entries)
nCreditDebit += entry.nCreditDebit; nCreditDebit += entry.nCreditDebit;
return nCreditDebit; return nCreditDebit;
@ -796,7 +799,7 @@ bool CWalletDB::LoadWallet()
pcursor->close(); pcursor->close();
} }
foreach(uint256 hash, vWalletUpgrade) BOOST_FOREACH(uint256 hash, vWalletUpgrade)
WriteTx(hash, mapWallet[hash]); WriteTx(hash, mapWallet[hash]);
printf("nFileVersion = %d\n", nFileVersion); printf("nFileVersion = %d\n", nFileVersion);

View file

@ -1,6 +1,16 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying // Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_DB_H
#define BITCOIN_DB_H
#include "key.h"
#include <map>
#include <string>
#include <vector>
#include <db_cxx.h>
class CTransaction; class CTransaction;
class CTxIndex; class CTxIndex;
@ -15,9 +25,9 @@ class CAccount;
class CAccountingEntry; class CAccountingEntry;
class CBlockLocator; class CBlockLocator;
extern map<string, string> mapAddressBook; extern std::map<std::string, std::string> mapAddressBook;
extern CCriticalSection cs_mapAddressBook; extern CCriticalSection cs_mapAddressBook;
extern vector<unsigned char> vchDefaultKey; extern std::vector<unsigned char> vchDefaultKey;
extern bool fClient; extern bool fClient;
extern int nBestHeight; extern int nBestHeight;
@ -27,7 +37,7 @@ extern DbEnv dbenv;
extern void DBFlush(bool fShutdown); extern void DBFlush(bool fShutdown);
extern vector<unsigned char> GetKeyFromKeyPool(); extern std::vector<unsigned char> GetKeyFromKeyPool();
extern int64 GetOldestKeyPoolTime(); extern int64 GetOldestKeyPoolTime();
@ -37,8 +47,8 @@ class CDB
{ {
protected: protected:
Db* pdb; Db* pdb;
string strFile; std::string strFile;
vector<DbTxn*> vTxn; std::vector<DbTxn*> vTxn;
bool fReadOnly; bool fReadOnly;
explicit CDB(const char* pszFile, const char* pszMode="r+"); explicit CDB(const char* pszFile, const char* pszMode="r+");
@ -247,12 +257,12 @@ public:
bool ReadVersion(int& nVersion) bool ReadVersion(int& nVersion)
{ {
nVersion = 0; nVersion = 0;
return Read(string("version"), nVersion); return Read(std::string("version"), nVersion);
} }
bool WriteVersion(int nVersion) bool WriteVersion(int nVersion)
{ {
return Write(string("version"), nVersion); return Write(std::string("version"), nVersion);
} }
}; };
@ -276,7 +286,7 @@ public:
bool AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight); bool AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight);
bool EraseTxIndex(const CTransaction& tx); bool EraseTxIndex(const CTransaction& tx);
bool ContainsTx(uint256 hash); bool ContainsTx(uint256 hash);
bool ReadOwnerTxes(uint160 hash160, int nHeight, vector<CTransaction>& vtx); bool ReadOwnerTxes(uint160 hash160, int nHeight, std::vector<CTransaction>& vtx);
bool ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex); bool ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex);
bool ReadDiskTx(uint256 hash, CTransaction& tx); bool ReadDiskTx(uint256 hash, CTransaction& tx);
bool ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex); bool ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex);
@ -318,14 +328,14 @@ class CKeyPool
{ {
public: public:
int64 nTime; int64 nTime;
vector<unsigned char> vchPubKey; std::vector<unsigned char> vchPubKey;
CKeyPool() CKeyPool()
{ {
nTime = GetTime(); nTime = GetTime();
} }
CKeyPool(const vector<unsigned char>& vchPubKeyIn) CKeyPool(const std::vector<unsigned char>& vchPubKeyIn)
{ {
nTime = GetTime(); nTime = GetTime();
vchPubKey = vchPubKeyIn; vchPubKey = vchPubKeyIn;
@ -353,101 +363,101 @@ private:
CWalletDB(const CWalletDB&); CWalletDB(const CWalletDB&);
void operator=(const CWalletDB&); void operator=(const CWalletDB&);
public: public:
bool ReadName(const string& strAddress, string& strName) bool ReadName(const std::string& strAddress, std::string& strName)
{ {
strName = ""; strName = "";
return Read(make_pair(string("name"), strAddress), strName); return Read(std::make_pair(std::string("name"), strAddress), strName);
} }
bool WriteName(const string& strAddress, const string& strName) bool WriteName(const std::string& strAddress, const std::string& strName)
{ {
CRITICAL_BLOCK(cs_mapAddressBook) CRITICAL_BLOCK(cs_mapAddressBook)
mapAddressBook[strAddress] = strName; mapAddressBook[strAddress] = strName;
nWalletDBUpdated++; nWalletDBUpdated++;
return Write(make_pair(string("name"), strAddress), strName); return Write(std::make_pair(std::string("name"), strAddress), strName);
} }
bool EraseName(const string& strAddress) bool EraseName(const std::string& strAddress)
{ {
// This should only be used for sending addresses, never for receiving addresses, // 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. // receiving addresses must always have an address book entry if they're not change return.
CRITICAL_BLOCK(cs_mapAddressBook) CRITICAL_BLOCK(cs_mapAddressBook)
mapAddressBook.erase(strAddress); mapAddressBook.erase(strAddress);
nWalletDBUpdated++; nWalletDBUpdated++;
return Erase(make_pair(string("name"), strAddress)); return Erase(std::make_pair(std::string("name"), strAddress));
} }
bool ReadTx(uint256 hash, CWalletTx& wtx) bool ReadTx(uint256 hash, CWalletTx& wtx)
{ {
return Read(make_pair(string("tx"), hash), wtx); return Read(std::make_pair(std::string("tx"), hash), wtx);
} }
bool WriteTx(uint256 hash, const CWalletTx& wtx) bool WriteTx(uint256 hash, const CWalletTx& wtx)
{ {
nWalletDBUpdated++; nWalletDBUpdated++;
return Write(make_pair(string("tx"), hash), wtx); return Write(std::make_pair(std::string("tx"), hash), wtx);
} }
bool EraseTx(uint256 hash) bool EraseTx(uint256 hash)
{ {
nWalletDBUpdated++; nWalletDBUpdated++;
return Erase(make_pair(string("tx"), hash)); return Erase(std::make_pair(std::string("tx"), hash));
} }
bool ReadKey(const vector<unsigned char>& vchPubKey, CPrivKey& vchPrivKey) bool ReadKey(const std::vector<unsigned char>& vchPubKey, CPrivKey& vchPrivKey)
{ {
vchPrivKey.clear(); vchPrivKey.clear();
return Read(make_pair(string("key"), vchPubKey), vchPrivKey); return Read(std::make_pair(std::string("key"), vchPubKey), vchPrivKey);
} }
bool WriteKey(const vector<unsigned char>& vchPubKey, const CPrivKey& vchPrivKey) bool WriteKey(const std::vector<unsigned char>& vchPubKey, const CPrivKey& vchPrivKey)
{ {
nWalletDBUpdated++; nWalletDBUpdated++;
return Write(make_pair(string("key"), vchPubKey), vchPrivKey, false); return Write(std::make_pair(std::string("key"), vchPubKey), vchPrivKey, false);
} }
bool WriteBestBlock(const CBlockLocator& locator) bool WriteBestBlock(const CBlockLocator& locator)
{ {
nWalletDBUpdated++; nWalletDBUpdated++;
return Write(string("bestblock"), locator); return Write(std::string("bestblock"), locator);
} }
bool ReadBestBlock(CBlockLocator& locator) bool ReadBestBlock(CBlockLocator& locator)
{ {
return Read(string("bestblock"), locator); return Read(std::string("bestblock"), locator);
} }
bool ReadDefaultKey(vector<unsigned char>& vchPubKey) bool ReadDefaultKey(std::vector<unsigned char>& vchPubKey)
{ {
vchPubKey.clear(); vchPubKey.clear();
return Read(string("defaultkey"), vchPubKey); return Read(std::string("defaultkey"), vchPubKey);
} }
bool WriteDefaultKey(const vector<unsigned char>& vchPubKey) bool WriteDefaultKey(const std::vector<unsigned char>& vchPubKey)
{ {
vchDefaultKey = vchPubKey; vchDefaultKey = vchPubKey;
nWalletDBUpdated++; nWalletDBUpdated++;
return Write(string("defaultkey"), vchPubKey); return Write(std::string("defaultkey"), vchPubKey);
} }
template<typename T> template<typename T>
bool ReadSetting(const string& strKey, T& value) bool ReadSetting(const std::string& strKey, T& value)
{ {
return Read(make_pair(string("setting"), strKey), value); return Read(std::make_pair(std::string("setting"), strKey), value);
} }
template<typename T> template<typename T>
bool WriteSetting(const string& strKey, const T& value) bool WriteSetting(const std::string& strKey, const T& value)
{ {
nWalletDBUpdated++; nWalletDBUpdated++;
return Write(make_pair(string("setting"), strKey), value); return Write(std::make_pair(std::string("setting"), strKey), value);
} }
bool ReadAccount(const string& strAccount, CAccount& account); bool ReadAccount(const std::string& strAccount, CAccount& account);
bool WriteAccount(const string& strAccount, const CAccount& account); bool WriteAccount(const std::string& strAccount, const CAccount& account);
bool WriteAccountingEntry(const CAccountingEntry& acentry); bool WriteAccountingEntry(const CAccountingEntry& acentry);
int64 GetAccountCreditDebit(const string& strAccount); int64 GetAccountCreditDebit(const std::string& strAccount);
void ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& acentries); void ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& acentries);
bool LoadWallet(); bool LoadWallet();
protected: protected:
@ -455,14 +465,14 @@ protected:
void KeepKey(int64 nIndex); void KeepKey(int64 nIndex);
static void ReturnKey(int64 nIndex); static void ReturnKey(int64 nIndex);
friend class CReserveKey; friend class CReserveKey;
friend vector<unsigned char> GetKeyFromKeyPool(); friend std::vector<unsigned char> GetKeyFromKeyPool();
friend int64 GetOldestKeyPoolTime(); friend int64 GetOldestKeyPoolTime();
}; };
bool LoadWallet(bool& fFirstRunRet); bool LoadWallet(bool& fFirstRunRet);
void BackupWallet(const string& strDest); void BackupWallet(const std::string& strDest);
inline bool SetAddressBookName(const string& strAddress, const string& strName) inline bool SetAddressBookName(const std::string& strAddress, const std::string& strName)
{ {
return CWalletDB().WriteName(strAddress, strName); return CWalletDB().WriteName(strAddress, strName);
} }
@ -471,7 +481,7 @@ class CReserveKey
{ {
protected: protected:
int64 nIndex; int64 nIndex;
vector<unsigned char> vchPubKey; std::vector<unsigned char> vchPubKey;
public: public:
CReserveKey() CReserveKey()
{ {
@ -484,7 +494,7 @@ public:
ReturnKey(); ReturnKey();
} }
vector<unsigned char> GetReservedKey() std::vector<unsigned char> GetReservedKey()
{ {
if (nIndex == -1) if (nIndex == -1)
{ {
@ -512,3 +522,5 @@ public:
vchPubKey.clear(); vchPubKey.clear();
} }
}; };
#endif

View file

@ -109,8 +109,6 @@
#pragma hdrstop #pragma hdrstop
using namespace std;
using namespace boost;
#include "strlcpy.h" #include "strlcpy.h"
#include "serialize.h" #include "serialize.h"
@ -133,6 +131,7 @@ using namespace boost;
#endif #endif
#include "init.h" #include "init.h"
#ifdef GUI
#include "xpm/addressbook16.xpm" #include "xpm/addressbook16.xpm"
#include "xpm/addressbook20.xpm" #include "xpm/addressbook20.xpm"
#include "xpm/bitcoin16.xpm" #include "xpm/bitcoin16.xpm"
@ -145,3 +144,4 @@ using namespace boost;
#include "xpm/send16noshadow.xpm" #include "xpm/send16noshadow.xpm"
#include "xpm/send20.xpm" #include "xpm/send20.xpm"
#include "xpm/about.xpm" #include "xpm/about.xpm"
#endif

View file

@ -1,14 +1,10 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying // Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "headers.h" #include "headers.h"
using namespace std;
using namespace boost;
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
// //
@ -71,7 +67,6 @@ void HandleSIGTERM(int)
// //
// Start // Start
// //
#ifndef GUI #ifndef GUI
int main(int argc, char* argv[]) int main(int argc, char* argv[])
{ {
@ -458,7 +453,7 @@ bool AppInit2(int argc, char* argv[])
if (mapArgs.count("-addnode")) if (mapArgs.count("-addnode"))
{ {
foreach(string strAddr, mapMultiArgs["-addnode"]) BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
{ {
CAddress addr(strAddr, fAllowDNS); CAddress addr(strAddr, fAllowDNS);
addr.nTime = 0; // so it won't relay unless successfully connected addr.nTime = 0; // so it won't relay unless successfully connected

View file

@ -1,7 +1,11 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying // Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_INIT_H
#define BITCOIN_INIT_H
void Shutdown(void* parg); void Shutdown(void* parg);
bool AppInit(int argc, char* argv[]); bool AppInit(int argc, char* argv[]);
bool AppInit2(int argc, char* argv[]); bool AppInit2(int argc, char* argv[]);
#endif

View file

@ -4,6 +4,9 @@
#include "headers.h" #include "headers.h"
using namespace std;
using namespace boost;
int nGotIRCAddresses = 0; int nGotIRCAddresses = 0;
bool fGotExternalIP = false; bool fGotExternalIP = false;

View file

@ -1,9 +1,13 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying // Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_IRC_H
#define BITCOIN_IRC_H
bool RecvLine(SOCKET hSocket, string& strLine); bool RecvLine(SOCKET hSocket, std::string& strLine);
void ThreadIRCSeed(void* parg); void ThreadIRCSeed(void* parg);
extern int nGotIRCAddresses; extern int nGotIRCAddresses;
extern bool fGotExternalIP; extern bool fGotExternalIP;
#endif

View file

@ -1,7 +1,12 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying // Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_KEY_H
#define BITCOIN_KEY_H
#include <openssl/ec.h>
#include <openssl/ecdsa.h>
#include <openssl/obj_mac.h>
// secp160k1 // secp160k1
// const unsigned int PRIVATE_KEY_SIZE = 192; // const unsigned int PRIVATE_KEY_SIZE = 192;
@ -36,7 +41,7 @@ public:
// secure_allocator is defined in serialize.h // secure_allocator is defined in serialize.h
typedef vector<unsigned char, secure_allocator<unsigned char> > CPrivKey; typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
@ -109,7 +114,7 @@ public:
return vchPrivKey; return vchPrivKey;
} }
bool SetPubKey(const vector<unsigned char>& vchPubKey) bool SetPubKey(const std::vector<unsigned char>& vchPubKey)
{ {
const unsigned char* pbegin = &vchPubKey[0]; const unsigned char* pbegin = &vchPubKey[0];
if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.size())) if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.size()))
@ -118,19 +123,19 @@ public:
return true; return true;
} }
vector<unsigned char> GetPubKey() const std::vector<unsigned char> GetPubKey() const
{ {
unsigned int nSize = i2o_ECPublicKey(pkey, NULL); unsigned int nSize = i2o_ECPublicKey(pkey, NULL);
if (!nSize) if (!nSize)
throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed"); throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
vector<unsigned char> vchPubKey(nSize, 0); std::vector<unsigned char> vchPubKey(nSize, 0);
unsigned char* pbegin = &vchPubKey[0]; unsigned char* pbegin = &vchPubKey[0];
if (i2o_ECPublicKey(pkey, &pbegin) != nSize) if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size"); throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
return vchPubKey; return vchPubKey;
} }
bool Sign(uint256 hash, vector<unsigned char>& vchSig) bool Sign(uint256 hash, std::vector<unsigned char>& vchSig)
{ {
vchSig.clear(); vchSig.clear();
unsigned char pchSig[10000]; unsigned char pchSig[10000];
@ -142,7 +147,7 @@ public:
return true; return true;
} }
bool Verify(uint256 hash, const vector<unsigned char>& vchSig) bool Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
{ {
// -1 = error, 0 = bad sig, 1 = good // -1 = error, 0 = bad sig, 1 = good
if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
@ -150,7 +155,7 @@ public:
return true; return true;
} }
static bool Sign(const CPrivKey& vchPrivKey, uint256 hash, vector<unsigned char>& vchSig) static bool Sign(const CPrivKey& vchPrivKey, uint256 hash, std::vector<unsigned char>& vchSig)
{ {
CKey key; CKey key;
if (!key.SetPrivKey(vchPrivKey)) if (!key.SetPrivKey(vchPrivKey))
@ -158,7 +163,7 @@ public:
return key.Sign(hash, vchSig); return key.Sign(hash, vchSig);
} }
static bool Verify(const vector<unsigned char>& vchPubKey, uint256 hash, const vector<unsigned char>& vchSig) static bool Verify(const std::vector<unsigned char>& vchPubKey, uint256 hash, const std::vector<unsigned char>& vchSig)
{ {
CKey key; CKey key;
if (!key.SetPubKey(vchPubKey)) if (!key.SetPubKey(vchPubKey))
@ -166,3 +171,5 @@ public:
return key.Verify(hash, vchSig); return key.Verify(hash, vchSig);
} }
}; };
#endif

View file

@ -1,13 +1,11 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying // Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "headers.h" #include "headers.h"
#include "cryptopp/sha.h" #include "cryptopp/sha.h"
using namespace std;
using namespace boost;
// //
// Global state // Global state
@ -156,7 +154,7 @@ bool AddToWallet(const CWalletTx& wtxIn)
// If default receiving address gets used, replace it with a new one // If default receiving address gets used, replace it with a new one
CScript scriptDefaultKey; CScript scriptDefaultKey;
scriptDefaultKey.SetBitcoinAddress(vchDefaultKey); scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
foreach(const CTxOut& txout, wtx.vout) BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{ {
if (txout.scriptPubKey == scriptDefaultKey) if (txout.scriptPubKey == scriptDefaultKey)
{ {
@ -244,7 +242,7 @@ void AddOrphanTx(const CDataStream& vMsg)
if (mapOrphanTransactions.count(hash)) if (mapOrphanTransactions.count(hash))
return; return;
CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg); CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
foreach(const CTxIn& txin, tx.vin) BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg)); mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
} }
@ -255,7 +253,7 @@ void EraseOrphanTx(uint256 hash)
const CDataStream* pvMsg = mapOrphanTransactions[hash]; const CDataStream* pvMsg = mapOrphanTransactions[hash];
CTransaction tx; CTransaction tx;
CDataStream(*pvMsg) >> tx; CDataStream(*pvMsg) >> tx;
foreach(const CTxIn& txin, tx.vin) BOOST_FOREACH(const CTxIn& txin, tx.vin)
{ {
for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash); for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);) mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
@ -426,7 +424,7 @@ void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, l
// Sent/received. Standard client will never generate a send-to-multiple-recipients, // Sent/received. Standard client will never generate a send-to-multiple-recipients,
// but non-standard clients might (so return a list of address/amount pairs) // but non-standard clients might (so return a list of address/amount pairs)
foreach(const CTxOut& txout, vout) BOOST_FOREACH(const CTxOut& txout, vout)
{ {
string address; string address;
uint160 hash160; uint160 hash160;
@ -471,13 +469,13 @@ void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, i
nGenerated = allGeneratedMature; nGenerated = allGeneratedMature;
if (strAccount == strSentAccount) if (strAccount == strSentAccount)
{ {
foreach(const PAIRTYPE(string,int64)& s, listSent) BOOST_FOREACH(const PAIRTYPE(string,int64)& s, listSent)
nSent += s.second; nSent += s.second;
nFee = allFee; nFee = allFee;
} }
CRITICAL_BLOCK(cs_mapAddressBook) CRITICAL_BLOCK(cs_mapAddressBook)
{ {
foreach(const PAIRTYPE(string,int64)& r, listReceived) BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
{ {
if (mapAddressBook.count(r.first)) if (mapAddressBook.count(r.first))
{ {
@ -557,7 +555,7 @@ void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
if (SetMerkleBranch() < COPY_DEPTH) if (SetMerkleBranch() < COPY_DEPTH)
{ {
vector<uint256> vWorkQueue; vector<uint256> vWorkQueue;
foreach(const CTxIn& txin, vin) BOOST_FOREACH(const CTxIn& txin, vin)
vWorkQueue.push_back(txin.prevout.hash); vWorkQueue.push_back(txin.prevout.hash);
// This critsect is OK because txdb is already open // This critsect is OK because txdb is already open
@ -576,7 +574,7 @@ void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
if (mapWallet.count(hash)) if (mapWallet.count(hash))
{ {
tx = mapWallet[hash]; tx = mapWallet[hash];
foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev) BOOST_FOREACH(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev; mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
} }
else if (mapWalletPrev.count(hash)) else if (mapWalletPrev.count(hash))
@ -597,7 +595,7 @@ void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
vtxPrev.push_back(tx); vtxPrev.push_back(tx);
if (nDepth < COPY_DEPTH) if (nDepth < COPY_DEPTH)
foreach(const CTxIn& txin, tx.vin) BOOST_FOREACH(const CTxIn& txin, tx.vin)
vWorkQueue.push_back(txin.prevout.hash); vWorkQueue.push_back(txin.prevout.hash);
} }
} }
@ -628,7 +626,7 @@ bool CTransaction::CheckTransaction() const
// Check for negative or overflow output values // Check for negative or overflow output values
int64 nValueOut = 0; int64 nValueOut = 0;
foreach(const CTxOut& txout, vout) BOOST_FOREACH(const CTxOut& txout, vout)
{ {
if (txout.nValue < 0) if (txout.nValue < 0)
return error("CTransaction::CheckTransaction() : txout.nValue negative"); return error("CTransaction::CheckTransaction() : txout.nValue negative");
@ -646,7 +644,7 @@ bool CTransaction::CheckTransaction() const
} }
else else
{ {
foreach(const CTxIn& txin, vin) BOOST_FOREACH(const CTxIn& txin, vin)
if (txin.prevout.IsNull()) if (txin.prevout.IsNull())
return error("CTransaction::CheckTransaction() : prevout is null"); return error("CTransaction::CheckTransaction() : prevout is null");
} }
@ -804,7 +802,7 @@ bool CTransaction::RemoveFromMemoryPool()
// Remove transaction from memory pool // Remove transaction from memory pool
CRITICAL_BLOCK(cs_mapTransactions) CRITICAL_BLOCK(cs_mapTransactions)
{ {
foreach(const CTxIn& txin, vin) BOOST_FOREACH(const CTxIn& txin, vin)
mapNextTx.erase(txin.prevout); mapNextTx.erase(txin.prevout);
mapTransactions.erase(GetHash()); mapTransactions.erase(GetHash());
nTransactionsUpdated++; nTransactionsUpdated++;
@ -872,7 +870,7 @@ bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
CRITICAL_BLOCK(cs_mapTransactions) CRITICAL_BLOCK(cs_mapTransactions)
{ {
// Add previous supporting transactions first // Add previous supporting transactions first
foreach(CMerkleTx& tx, vtxPrev) BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
{ {
if (!tx.IsCoinBase()) if (!tx.IsCoinBase())
{ {
@ -897,7 +895,7 @@ int ScanForWalletTransactions(CBlockIndex* pindexStart)
{ {
CBlock block; CBlock block;
block.ReadFromDisk(pindex, true); block.ReadFromDisk(pindex, true);
foreach(CTransaction& tx, block.vtx) BOOST_FOREACH(CTransaction& tx, block.vtx)
{ {
if (AddToWalletIfInvolvingMe(tx, &block)) if (AddToWalletIfInvolvingMe(tx, &block))
ret++; ret++;
@ -916,7 +914,7 @@ void ReacceptWalletTransactions()
{ {
fRepeat = false; fRepeat = false;
vector<CDiskTxPos> vMissingTx; vector<CDiskTxPos> vMissingTx;
foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{ {
CWalletTx& wtx = item.second; CWalletTx& wtx = item.second;
if (wtx.IsCoinBase() && wtx.IsSpent(0)) if (wtx.IsCoinBase() && wtx.IsSpent(0))
@ -969,7 +967,7 @@ void ReacceptWalletTransactions()
void CWalletTx::RelayWalletTransaction(CTxDB& txdb) void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
{ {
foreach(const CMerkleTx& tx, vtxPrev) BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
{ {
if (!tx.IsCoinBase()) if (!tx.IsCoinBase())
{ {
@ -1014,7 +1012,7 @@ void ResendWalletTransactions()
{ {
// Sort them in chronological order // Sort them in chronological order
multimap<unsigned int, CWalletTx*> mapSorted; multimap<unsigned int, CWalletTx*> mapSorted;
foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{ {
CWalletTx& wtx = item.second; CWalletTx& wtx = item.second;
// Don't rebroadcast until it's had plenty of time that // Don't rebroadcast until it's had plenty of time that
@ -1022,7 +1020,7 @@ void ResendWalletTransactions()
if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60) if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
} }
foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted) BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
{ {
CWalletTx& wtx = *item.second; CWalletTx& wtx = *item.second;
wtx.RelayWalletTransaction(txdb); wtx.RelayWalletTransaction(txdb);
@ -1198,7 +1196,7 @@ bool CTransaction::DisconnectInputs(CTxDB& txdb)
// Relinquish previous transactions' spent pointers // Relinquish previous transactions' spent pointers
if (!IsCoinBase()) if (!IsCoinBase())
{ {
foreach(const CTxIn& txin, vin) BOOST_FOREACH(const CTxIn& txin, vin)
{ {
COutPoint prevout = txin.prevout; COutPoint prevout = txin.prevout;
@ -1421,7 +1419,7 @@ bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
map<uint256, CTxIndex> mapUnused; map<uint256, CTxIndex> mapUnused;
int64 nFees = 0; int64 nFees = 0;
foreach(CTransaction& tx, vtx) BOOST_FOREACH(CTransaction& tx, vtx)
{ {
CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos); CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
nTxPos += ::GetSerializeSize(tx, SER_DISK); nTxPos += ::GetSerializeSize(tx, SER_DISK);
@ -1444,7 +1442,7 @@ bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
} }
// Watch for transactions paying to me // Watch for transactions paying to me
foreach(CTransaction& tx, vtx) BOOST_FOREACH(CTransaction& tx, vtx)
AddToWalletIfInvolvingMe(tx, this, true); AddToWalletIfInvolvingMe(tx, this, true);
return true; return true;
@ -1481,7 +1479,7 @@ bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
// Disconnect shorter branch // Disconnect shorter branch
vector<CTransaction> vResurrect; vector<CTransaction> vResurrect;
foreach(CBlockIndex* pindex, vDisconnect) BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
{ {
CBlock block; CBlock block;
if (!block.ReadFromDisk(pindex)) if (!block.ReadFromDisk(pindex))
@ -1490,7 +1488,7 @@ bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
return error("Reorganize() : DisconnectBlock failed"); return error("Reorganize() : DisconnectBlock failed");
// Queue memory transactions to resurrect // Queue memory transactions to resurrect
foreach(const CTransaction& tx, block.vtx) BOOST_FOREACH(const CTransaction& tx, block.vtx)
if (!tx.IsCoinBase()) if (!tx.IsCoinBase())
vResurrect.push_back(tx); vResurrect.push_back(tx);
} }
@ -1511,7 +1509,7 @@ bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
} }
// Queue memory transactions to delete // Queue memory transactions to delete
foreach(const CTransaction& tx, block.vtx) BOOST_FOREACH(const CTransaction& tx, block.vtx)
vDelete.push_back(tx); vDelete.push_back(tx);
} }
if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash())) if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
@ -1522,21 +1520,21 @@ bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
return error("Reorganize() : TxnCommit failed"); return error("Reorganize() : TxnCommit failed");
// Disconnect shorter branch // Disconnect shorter branch
foreach(CBlockIndex* pindex, vDisconnect) BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
if (pindex->pprev) if (pindex->pprev)
pindex->pprev->pnext = NULL; pindex->pprev->pnext = NULL;
// Connect longer branch // Connect longer branch
foreach(CBlockIndex* pindex, vConnect) BOOST_FOREACH(CBlockIndex* pindex, vConnect)
if (pindex->pprev) if (pindex->pprev)
pindex->pprev->pnext = pindex; pindex->pprev->pnext = pindex;
// Resurrect memory transactions that were in the disconnected branch // Resurrect memory transactions that were in the disconnected branch
foreach(CTransaction& tx, vResurrect) BOOST_FOREACH(CTransaction& tx, vResurrect)
tx.AcceptToMemoryPool(txdb, false); tx.AcceptToMemoryPool(txdb, false);
// Delete redundant memory transactions that are in the connected branch // Delete redundant memory transactions that are in the connected branch
foreach(CTransaction& tx, vDelete) BOOST_FOREACH(CTransaction& tx, vDelete)
tx.RemoveFromMemoryPool(); tx.RemoveFromMemoryPool();
return true; return true;
@ -1571,7 +1569,7 @@ bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
pindexNew->pprev->pnext = pindexNew; pindexNew->pprev->pnext = pindexNew;
// Delete redundant memory transactions // Delete redundant memory transactions
foreach(CTransaction& tx, vtx) BOOST_FOREACH(CTransaction& tx, vtx)
tx.RemoveFromMemoryPool(); tx.RemoveFromMemoryPool();
} }
else else
@ -1682,7 +1680,7 @@ bool CBlock::CheckBlock() const
return error("CheckBlock() : more than one coinbase"); return error("CheckBlock() : more than one coinbase");
// Check transactions // Check transactions
foreach(const CTransaction& tx, vtx) BOOST_FOREACH(const CTransaction& tx, vtx)
if (!tx.CheckTransaction()) if (!tx.CheckTransaction())
return error("CheckBlock() : CheckTransaction failed"); return error("CheckBlock() : CheckTransaction failed");
@ -1720,7 +1718,7 @@ bool CBlock::AcceptBlock()
return error("AcceptBlock() : block's timestamp is too early"); return error("AcceptBlock() : block's timestamp is too early");
// Check that all transactions are finalized // Check that all transactions are finalized
foreach(const CTransaction& tx, vtx) BOOST_FOREACH(const CTransaction& tx, vtx)
if (!tx.IsFinal(nHeight, GetBlockTime())) if (!tx.IsFinal(nHeight, GetBlockTime()))
return error("AcceptBlock() : contains a non-final transaction"); return error("AcceptBlock() : contains a non-final transaction");
@ -1748,7 +1746,7 @@ bool CBlock::AcceptBlock()
// Relay inventory, but don't relay old inventory during initial block download // Relay inventory, but don't relay old inventory during initial block download
if (hashBestChain == hash) if (hashBestChain == hash)
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 118000)) if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 118000))
pnode->PushInventory(CInv(MSG_BLOCK, hash)); pnode->PushInventory(CInv(MSG_BLOCK, hash));
@ -2120,7 +2118,7 @@ string GetWarnings(string strFor)
// Alerts // Alerts
CRITICAL_BLOCK(cs_mapAlerts) CRITICAL_BLOCK(cs_mapAlerts)
{ {
foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{ {
const CAlert& alert = item.second; const CAlert& alert = item.second;
if (alert.AppliesToMe() && alert.nPriority > nPriority) if (alert.AppliesToMe() && alert.nPriority > nPriority)
@ -2167,7 +2165,7 @@ bool CAlert::ProcessAlert()
} }
// Check if this alert has been cancelled // Check if this alert has been cancelled
foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{ {
const CAlert& alert = item.second; const CAlert& alert = item.second;
if (alert.Cancels(*this)) if (alert.Cancels(*this))
@ -2431,7 +2429,7 @@ bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
// Relay alerts // Relay alerts
CRITICAL_BLOCK(cs_mapAlerts) CRITICAL_BLOCK(cs_mapAlerts)
foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
item.second.RelayTo(pfrom); item.second.RelayTo(pfrom);
pfrom->fSuccessfullyConnected = true; pfrom->fSuccessfullyConnected = true;
@ -2469,7 +2467,7 @@ bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
// Store the new addresses // Store the new addresses
int64 nNow = GetAdjustedTime(); int64 nNow = GetAdjustedTime();
int64 nSince = nNow - 10 * 60; int64 nSince = nNow - 10 * 60;
foreach(CAddress& addr, vAddr) BOOST_FOREACH(CAddress& addr, vAddr)
{ {
if (fShutdown) if (fShutdown)
return true; return true;
@ -2493,7 +2491,7 @@ bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60)); uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
hashRand = Hash(BEGIN(hashRand), END(hashRand)); hashRand = Hash(BEGIN(hashRand), END(hashRand));
multimap<uint256, CNode*> mapMix; multimap<uint256, CNode*> mapMix;
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
{ {
if (pnode->nVersion < 31402) if (pnode->nVersion < 31402)
continue; continue;
@ -2522,7 +2520,7 @@ bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
return error("message inv size() = %d", vInv.size()); return error("message inv size() = %d", vInv.size());
CTxDB txdb("r"); CTxDB txdb("r");
foreach(const CInv& inv, vInv) BOOST_FOREACH(const CInv& inv, vInv)
{ {
if (fShutdown) if (fShutdown)
return true; return true;
@ -2554,7 +2552,7 @@ bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
if (vInv.size() > 50000) if (vInv.size() > 50000)
return error("message getdata size() = %d", vInv.size()); return error("message getdata size() = %d", vInv.size());
foreach(const CInv& inv, vInv) BOOST_FOREACH(const CInv& inv, vInv)
{ {
if (fShutdown) if (fShutdown)
return true; return true;
@ -2717,7 +2715,7 @@ bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
} }
} }
foreach(uint256 hash, vWorkQueue) BOOST_FOREACH(uint256 hash, vWorkQueue)
EraseOrphanTx(hash); EraseOrphanTx(hash);
} }
else if (fMissingInputs) else if (fMissingInputs)
@ -2752,13 +2750,13 @@ bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
CRITICAL_BLOCK(cs_mapAddresses) CRITICAL_BLOCK(cs_mapAddresses)
{ {
unsigned int nCount = 0; unsigned int nCount = 0;
foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses) BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
{ {
const CAddress& addr = item.second; const CAddress& addr = item.second;
if (addr.nTime > nSince) if (addr.nTime > nSince)
nCount++; nCount++;
} }
foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses) BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
{ {
const CAddress& addr = item.second; const CAddress& addr = item.second;
if (addr.nTime > nSince && GetRand(nCount) < 2500) if (addr.nTime > nSince && GetRand(nCount) < 2500)
@ -2861,7 +2859,7 @@ bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
// Relay // Relay
pfrom->setKnown.insert(alert.GetHash()); pfrom->setKnown.insert(alert.GetHash());
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode); alert.RelayTo(pnode);
} }
} }
@ -2912,7 +2910,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
nLastRebroadcast = GetTime(); nLastRebroadcast = GetTime();
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
{ {
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
{ {
// Periodically clear setAddrKnown to allow refresh broadcasts // Periodically clear setAddrKnown to allow refresh broadcasts
pnode->setAddrKnown.clear(); pnode->setAddrKnown.clear();
@ -2964,7 +2962,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
{ {
vector<CAddress> vAddr; vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size()); vAddr.reserve(pto->vAddrToSend.size());
foreach(const CAddress& addr, pto->vAddrToSend) BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
{ {
// returns true if wasn't already contained in the set // returns true if wasn't already contained in the set
if (pto->setAddrKnown.insert(addr).second) if (pto->setAddrKnown.insert(addr).second)
@ -2993,7 +2991,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
{ {
vInv.reserve(pto->vInventoryToSend.size()); vInv.reserve(pto->vInventoryToSend.size());
vInvWait.reserve(pto->vInventoryToSend.size()); vInvWait.reserve(pto->vInventoryToSend.size());
foreach(const CInv& inv, pto->vInventoryToSend) BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
{ {
if (pto->setInventoryKnown.count(inv)) if (pto->setInventoryKnown.count(inv))
continue; continue;
@ -3220,7 +3218,7 @@ public:
void print() const void print() const
{ {
printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority); printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
foreach(uint256 hash, setDependsOn) BOOST_FOREACH(uint256 hash, setDependsOn)
printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str()); printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
} }
}; };
@ -3264,7 +3262,7 @@ CBlock* CreateNewBlock(CReserveKey& reservekey)
COrphan* porphan = NULL; COrphan* porphan = NULL;
double dPriority = 0; double dPriority = 0;
foreach(const CTxIn& txin, tx.vin) BOOST_FOREACH(const CTxIn& txin, tx.vin)
{ {
// Read prev transaction // Read prev transaction
CTransaction txPrev; CTransaction txPrev;
@ -3349,7 +3347,7 @@ CBlock* CreateNewBlock(CReserveKey& reservekey)
uint256 hash = tx.GetHash(); uint256 hash = tx.GetHash();
if (mapDependers.count(hash)) if (mapDependers.count(hash))
{ {
foreach(COrphan* porphan, mapDependers[hash]) BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
{ {
if (!porphan->setDependsOn.empty()) if (!porphan->setDependsOn.empty())
{ {
@ -3679,7 +3677,7 @@ bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<
vCoins.push_back(&(*it).second); vCoins.push_back(&(*it).second);
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
foreach(CWalletTx* pcoin, vCoins) BOOST_FOREACH(CWalletTx* pcoin, vCoins)
{ {
if (!pcoin->IsFinal() || !pcoin->IsConfirmed()) if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
continue; continue;
@ -3817,7 +3815,7 @@ bool SelectCoins(int64 nTargetValue, set<pair<CWalletTx*,unsigned int> >& setCoi
bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet) bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
{ {
int64 nValue = 0; int64 nValue = 0;
foreach (const PAIRTYPE(CScript, int64)& s, vecSend) BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
{ {
if (nValue < 0) if (nValue < 0)
return false; return false;
@ -3842,7 +3840,7 @@ bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx&
int64 nTotalValue = nValue + nFeeRet; int64 nTotalValue = nValue + nFeeRet;
double dPriority = 0; double dPriority = 0;
// vouts to the payees // vouts to the payees
foreach (const PAIRTYPE(CScript, int64)& s, vecSend) BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
wtxNew.vout.push_back(CTxOut(s.second, s.first)); wtxNew.vout.push_back(CTxOut(s.second, s.first));
// Choose coins to use // Choose coins to use
@ -3850,7 +3848,7 @@ bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx&
int64 nValueIn = 0; int64 nValueIn = 0;
if (!SelectCoins(nTotalValue, setCoins, nValueIn)) if (!SelectCoins(nTotalValue, setCoins, nValueIn))
return false; return false;
foreach(PAIRTYPE(CWalletTx*, unsigned int) pcoin, setCoins) BOOST_FOREACH(PAIRTYPE(CWalletTx*, unsigned int) pcoin, setCoins)
{ {
int64 nCredit = pcoin.first->vout[pcoin.second].nValue; int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain(); dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
@ -3886,12 +3884,12 @@ bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx&
reservekey.ReturnKey(); reservekey.ReturnKey();
// Fill vin // Fill vin
foreach(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins) BOOST_FOREACH(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)
wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second)); wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
// Sign // Sign
int nIn = 0; int nIn = 0;
foreach(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins) BOOST_FOREACH(const PAIRTYPE(CWalletTx*,unsigned int)& coin, setCoins)
if (!SignSignature(*coin.first, wtxNew, nIn++)) if (!SignSignature(*coin.first, wtxNew, nIn++))
return false; return false;
@ -3951,7 +3949,7 @@ bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
// Mark old coins as spent // Mark old coins as spent
set<CWalletTx*> setCoins; set<CWalletTx*> setCoins;
foreach(const CTxIn& txin, wtxNew.vin) BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
{ {
CWalletTx &pcoin = mapWallet[txin.prevout.hash]; CWalletTx &pcoin = mapWallet[txin.prevout.hash];
pcoin.MarkSpent(txin.prevout.n); pcoin.MarkSpent(txin.prevout.n);

View file

@ -1,6 +1,16 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying // Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_MAIN_H
#define BITCOIN_MAIN_H
#include "bignum.h"
#include "net.h"
#include "key.h"
#include "db.h"
#include "script.h"
#include <list>
class COutPoint; class COutPoint;
class CInPoint; class CInPoint;
@ -35,7 +45,7 @@ static const int fHaveUPnP = false;
extern CCriticalSection cs_main; extern CCriticalSection cs_main;
extern map<uint256, CBlockIndex*> mapBlockIndex; extern std::map<uint256, CBlockIndex*> mapBlockIndex;
extern uint256 hashGenesisBlock; extern uint256 hashGenesisBlock;
extern CBigNum bnProofOfWorkLimit; extern CBigNum bnProofOfWorkLimit;
extern CBlockIndex* pindexGenesisBlock; extern CBlockIndex* pindexGenesisBlock;
@ -45,11 +55,11 @@ extern CBigNum bnBestInvalidWork;
extern uint256 hashBestChain; extern uint256 hashBestChain;
extern CBlockIndex* pindexBest; extern CBlockIndex* pindexBest;
extern unsigned int nTransactionsUpdated; extern unsigned int nTransactionsUpdated;
extern map<uint256, int> mapRequestCount; extern std::map<uint256, int> mapRequestCount;
extern CCriticalSection cs_mapRequestCount; extern CCriticalSection cs_mapRequestCount;
extern map<string, string> mapAddressBook; extern std::map<std::string, std::string> mapAddressBook;
extern CCriticalSection cs_mapAddressBook; extern CCriticalSection cs_mapAddressBook;
extern vector<unsigned char> vchDefaultKey; extern std::vector<unsigned char> vchDefaultKey;
extern double dHashesPerSec; extern double dHashesPerSec;
extern int64 nHPSTimerStart; extern int64 nHPSTimerStart;
@ -73,7 +83,7 @@ bool CheckDiskSpace(uint64 nAdditionalBytes=0);
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb"); FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
FILE* AppendBlockFile(unsigned int& nFileRet); FILE* AppendBlockFile(unsigned int& nFileRet);
bool AddKey(const CKey& key); bool AddKey(const CKey& key);
vector<unsigned char> GenerateNewKey(); std::vector<unsigned char> GenerateNewKey();
bool AddToWallet(const CWalletTx& wtxIn); bool AddToWallet(const CWalletTx& wtxIn);
void WalletUpdateSpent(const COutPoint& prevout); void WalletUpdateSpent(const COutPoint& prevout);
int ScanForWalletTransactions(CBlockIndex* pindexStart); int ScanForWalletTransactions(CBlockIndex* pindexStart);
@ -81,15 +91,15 @@ void ReacceptWalletTransactions();
bool LoadBlockIndex(bool fAllowNew=true); bool LoadBlockIndex(bool fAllowNew=true);
void PrintBlockTree(); void PrintBlockTree();
bool ProcessMessages(CNode* pfrom); bool ProcessMessages(CNode* pfrom);
bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv); bool ProcessMessage(CNode* pfrom, std::string strCommand, CDataStream& vRecv);
bool SendMessages(CNode* pto, bool fSendTrickle); bool SendMessages(CNode* pto, bool fSendTrickle);
int64 GetBalance(); int64 GetBalance();
bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet); 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 CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey); bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
bool BroadcastTransaction(CWalletTx& wtxNew); bool BroadcastTransaction(CWalletTx& wtxNew);
string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false); std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
string SendMoneyToBitcoinAddress(string strAddress, 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 GenerateBitcoins(bool fGenerate);
void ThreadBitcoinMiner(void* parg); void ThreadBitcoinMiner(void* parg);
CBlock* CreateNewBlock(CReserveKey& reservekey); CBlock* CreateNewBlock(CReserveKey& reservekey);
@ -99,7 +109,7 @@ bool CheckWork(CBlock* pblock, CReserveKey& reservekey);
void BitcoinMiner(); void BitcoinMiner();
bool CheckProofOfWork(uint256 hash, unsigned int nBits); bool CheckProofOfWork(uint256 hash, unsigned int nBits);
bool IsInitialBlockDownload(); bool IsInitialBlockDownload();
string GetWarnings(string strFor); std::string GetWarnings(std::string strFor);
@ -147,7 +157,7 @@ public:
return !(a == b); return !(a == b);
} }
string ToString() const std::string ToString() const
{ {
if (IsNull()) if (IsNull())
return strprintf("null"); return strprintf("null");
@ -206,7 +216,7 @@ public:
return !(a == b); return !(a == b);
} }
string ToString() const std::string ToString() const
{ {
return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n); return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
} }
@ -275,9 +285,9 @@ public:
return !(a == b); return !(a == b);
} }
string ToString() const std::string ToString() const
{ {
string str; std::string str;
str += strprintf("CTxIn("); str += strprintf("CTxIn(");
str += prevout.ToString(); str += prevout.ToString();
if (prevout.IsNull()) if (prevout.IsNull())
@ -353,14 +363,14 @@ public:
int64 GetCredit() const int64 GetCredit() const
{ {
if (!MoneyRange(nValue)) if (!MoneyRange(nValue))
throw runtime_error("CTxOut::GetCredit() : value out of range"); throw std::runtime_error("CTxOut::GetCredit() : value out of range");
return (IsMine() ? nValue : 0); return (IsMine() ? nValue : 0);
} }
bool IsChange() const bool IsChange() const
{ {
// On a debit transaction, a txout that's mine but isn't in the address book is change // On a debit transaction, a txout that's mine but isn't in the address book is change
vector<unsigned char> vchPubKey; std::vector<unsigned char> vchPubKey;
if (ExtractPubKey(scriptPubKey, true, vchPubKey)) if (ExtractPubKey(scriptPubKey, true, vchPubKey))
CRITICAL_BLOCK(cs_mapAddressBook) CRITICAL_BLOCK(cs_mapAddressBook)
if (!mapAddressBook.count(PubKeyToAddress(vchPubKey))) if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
@ -371,7 +381,7 @@ public:
int64 GetChange() const int64 GetChange() const
{ {
if (!MoneyRange(nValue)) if (!MoneyRange(nValue))
throw runtime_error("CTxOut::GetChange() : value out of range"); throw std::runtime_error("CTxOut::GetChange() : value out of range");
return (IsChange() ? nValue : 0); return (IsChange() ? nValue : 0);
} }
@ -386,7 +396,7 @@ public:
return !(a == b); return !(a == b);
} }
string ToString() const std::string ToString() const
{ {
if (scriptPubKey.size() < 6) if (scriptPubKey.size() < 6)
return "CTxOut(error)"; return "CTxOut(error)";
@ -410,8 +420,8 @@ class CTransaction
{ {
public: public:
int nVersion; int nVersion;
vector<CTxIn> vin; std::vector<CTxIn> vin;
vector<CTxOut> vout; std::vector<CTxOut> vout;
unsigned int nLockTime; unsigned int nLockTime;
@ -458,7 +468,7 @@ public:
nBlockTime = GetAdjustedTime(); nBlockTime = GetAdjustedTime();
if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime)) if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
return true; return true;
foreach(const CTxIn& txin, vin) BOOST_FOREACH(const CTxIn& txin, vin)
if (!txin.IsFinal()) if (!txin.IsFinal())
return false; return false;
return true; return true;
@ -501,19 +511,19 @@ public:
int GetSigOpCount() const int GetSigOpCount() const
{ {
int n = 0; int n = 0;
foreach(const CTxIn& txin, vin) BOOST_FOREACH(const CTxIn& txin, vin)
n += txin.scriptSig.GetSigOpCount(); n += txin.scriptSig.GetSigOpCount();
foreach(const CTxOut& txout, vout) BOOST_FOREACH(const CTxOut& txout, vout)
n += txout.scriptPubKey.GetSigOpCount(); n += txout.scriptPubKey.GetSigOpCount();
return n; return n;
} }
bool IsStandard() const bool IsStandard() const
{ {
foreach(const CTxIn& txin, vin) BOOST_FOREACH(const CTxIn& txin, vin)
if (!txin.scriptSig.IsPushOnly()) if (!txin.scriptSig.IsPushOnly())
return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str()); return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
foreach(const CTxOut& txout, vout) BOOST_FOREACH(const CTxOut& txout, vout)
if (!::IsStandard(txout.scriptPubKey)) if (!::IsStandard(txout.scriptPubKey))
return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str()); return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
return true; return true;
@ -521,7 +531,7 @@ public:
bool IsMine() const bool IsMine() const
{ {
foreach(const CTxOut& txout, vout) BOOST_FOREACH(const CTxOut& txout, vout)
if (txout.IsMine()) if (txout.IsMine())
return true; return true;
return false; return false;
@ -535,11 +545,11 @@ public:
int64 GetDebit() const int64 GetDebit() const
{ {
int64 nDebit = 0; int64 nDebit = 0;
foreach(const CTxIn& txin, vin) BOOST_FOREACH(const CTxIn& txin, vin)
{ {
nDebit += txin.GetDebit(); nDebit += txin.GetDebit();
if (!MoneyRange(nDebit)) if (!MoneyRange(nDebit))
throw runtime_error("CTransaction::GetDebit() : value out of range"); throw std::runtime_error("CTransaction::GetDebit() : value out of range");
} }
return nDebit; return nDebit;
} }
@ -547,11 +557,11 @@ public:
int64 GetCredit() const int64 GetCredit() const
{ {
int64 nCredit = 0; int64 nCredit = 0;
foreach(const CTxOut& txout, vout) BOOST_FOREACH(const CTxOut& txout, vout)
{ {
nCredit += txout.GetCredit(); nCredit += txout.GetCredit();
if (!MoneyRange(nCredit)) if (!MoneyRange(nCredit))
throw runtime_error("CTransaction::GetCredit() : value out of range"); throw std::runtime_error("CTransaction::GetCredit() : value out of range");
} }
return nCredit; return nCredit;
} }
@ -561,11 +571,11 @@ public:
if (IsCoinBase()) if (IsCoinBase())
return 0; return 0;
int64 nChange = 0; int64 nChange = 0;
foreach(const CTxOut& txout, vout) BOOST_FOREACH(const CTxOut& txout, vout)
{ {
nChange += txout.GetChange(); nChange += txout.GetChange();
if (!MoneyRange(nChange)) if (!MoneyRange(nChange))
throw runtime_error("CTransaction::GetChange() : value out of range"); throw std::runtime_error("CTransaction::GetChange() : value out of range");
} }
return nChange; return nChange;
} }
@ -573,11 +583,11 @@ public:
int64 GetValueOut() const int64 GetValueOut() const
{ {
int64 nValueOut = 0; int64 nValueOut = 0;
foreach(const CTxOut& txout, vout) BOOST_FOREACH(const CTxOut& txout, vout)
{ {
nValueOut += txout.nValue; nValueOut += txout.nValue;
if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut)) if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
throw runtime_error("CTransaction::GetValueOut() : value out of range"); throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
} }
return nValueOut; return nValueOut;
} }
@ -615,7 +625,7 @@ public:
// To limit dust spam, require MIN_TX_FEE if any output is less than 0.01 // To limit dust spam, require MIN_TX_FEE if any output is less than 0.01
if (nMinFee < MIN_TX_FEE) if (nMinFee < MIN_TX_FEE)
foreach(const CTxOut& txout, vout) BOOST_FOREACH(const CTxOut& txout, vout)
if (txout.nValue < CENT) if (txout.nValue < CENT)
nMinFee = MIN_TX_FEE; nMinFee = MIN_TX_FEE;
@ -668,9 +678,9 @@ public:
} }
string ToString() const std::string ToString() const
{ {
string str; std::string str;
str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n", str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
GetHash().ToString().substr(0,10).c_str(), GetHash().ToString().substr(0,10).c_str(),
nVersion, nVersion,
@ -694,7 +704,7 @@ public:
bool ReadFromDisk(CTxDB& txdb, COutPoint prevout); bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
bool ReadFromDisk(COutPoint prevout); bool ReadFromDisk(COutPoint prevout);
bool DisconnectInputs(CTxDB& txdb); bool DisconnectInputs(CTxDB& txdb);
bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0); CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
bool ClientConnectInputs(); bool ClientConnectInputs();
bool CheckTransaction() const; bool CheckTransaction() const;
@ -721,7 +731,7 @@ class CMerkleTx : public CTransaction
{ {
public: public:
uint256 hashBlock; uint256 hashBlock;
vector<uint256> vMerkleBranch; std::vector<uint256> vMerkleBranch;
int nIndex; int nIndex;
// memory only // memory only
@ -776,14 +786,14 @@ public:
class CWalletTx : public CMerkleTx class CWalletTx : public CMerkleTx
{ {
public: public:
vector<CMerkleTx> vtxPrev; std::vector<CMerkleTx> vtxPrev;
map<string, string> mapValue; std::map<std::string, std::string> mapValue;
vector<pair<string, string> > vOrderForm; std::vector<std::pair<std::string, std::string> > vOrderForm;
unsigned int fTimeReceivedIsTxTime; unsigned int fTimeReceivedIsTxTime;
unsigned int nTimeReceived; // time received by this node unsigned int nTimeReceived; // time received by this node
char fFromMe; char fFromMe;
string strFromAccount; std::string strFromAccount;
vector<char> vfSpent; std::vector<char> vfSpent;
// memory only // memory only
mutable char fDebitCached; mutable char fDebitCached;
@ -850,8 +860,8 @@ public:
{ {
pthis->mapValue["fromaccount"] = pthis->strFromAccount; pthis->mapValue["fromaccount"] = pthis->strFromAccount;
string str; std::string str;
foreach(char f, vfSpent) BOOST_FOREACH(char f, vfSpent)
{ {
str += (f ? '1' : '0'); str += (f ? '1' : '0');
if (f) if (f)
@ -874,7 +884,7 @@ public:
pthis->strFromAccount = pthis->mapValue["fromaccount"]; pthis->strFromAccount = pthis->mapValue["fromaccount"];
if (mapValue.count("spent")) if (mapValue.count("spent"))
foreach(char c, pthis->mapValue["spent"]) BOOST_FOREACH(char c, pthis->mapValue["spent"])
pthis->vfSpent.push_back(c != '0'); pthis->vfSpent.push_back(c != '0');
else else
pthis->vfSpent.assign(vout.size(), fSpent); pthis->vfSpent.assign(vout.size(), fSpent);
@ -887,7 +897,7 @@ public:
// marks certain txout's as spent // marks certain txout's as spent
// returns true if any update took place // returns true if any update took place
bool UpdateSpent(const vector<char>& vfNewSpent) bool UpdateSpent(const std::vector<char>& vfNewSpent)
{ {
bool fReturn = false; bool fReturn = false;
for (int i=0; i < vfNewSpent.size(); i++) for (int i=0; i < vfNewSpent.size(); i++)
@ -916,7 +926,7 @@ public:
void MarkSpent(unsigned int nOut) void MarkSpent(unsigned int nOut)
{ {
if (nOut >= vout.size()) if (nOut >= vout.size())
throw runtime_error("CWalletTx::MarkSpent() : nOut out of range"); throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
vfSpent.resize(vout.size()); vfSpent.resize(vout.size());
if (!vfSpent[nOut]) if (!vfSpent[nOut])
{ {
@ -928,7 +938,7 @@ public:
bool IsSpent(unsigned int nOut) const bool IsSpent(unsigned int nOut) const
{ {
if (nOut >= vout.size()) if (nOut >= vout.size())
throw runtime_error("CWalletTx::IsSpent() : nOut out of range"); throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
if (nOut >= vfSpent.size()) if (nOut >= vfSpent.size())
return false; return false;
return (!!vfSpent[nOut]); return (!!vfSpent[nOut]);
@ -976,7 +986,7 @@ public:
const CTxOut &txout = vout[i]; const CTxOut &txout = vout[i];
nCredit += txout.GetCredit(); nCredit += txout.GetCredit();
if (!MoneyRange(nCredit)) if (!MoneyRange(nCredit))
throw runtime_error("CWalletTx::GetAvailableCredit() : value out of range"); throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
} }
} }
@ -995,10 +1005,10 @@ public:
return nChangeCached; return nChangeCached;
} }
void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string /* address */, int64> >& listReceived, void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
list<pair<string /* address */, int64> >& listSent, int64& nFee, string& strSentAccount) const; std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
void GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived, void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
int64& nSent, int64& nFee) const; int64& nSent, int64& nFee) const;
bool IsFromMe() const bool IsFromMe() const
@ -1018,8 +1028,8 @@ public:
// If no confirmations but it's from us, we can still // If no confirmations but it's from us, we can still
// consider it confirmed if all dependencies are confirmed // consider it confirmed if all dependencies are confirmed
map<uint256, const CMerkleTx*> mapPrev; std::map<uint256, const CMerkleTx*> mapPrev;
vector<const CMerkleTx*> vWorkQueue; std::vector<const CMerkleTx*> vWorkQueue;
vWorkQueue.reserve(vtxPrev.size()+1); vWorkQueue.reserve(vtxPrev.size()+1);
vWorkQueue.push_back(this); vWorkQueue.push_back(this);
for (int i = 0; i < vWorkQueue.size(); i++) for (int i = 0; i < vWorkQueue.size(); i++)
@ -1034,10 +1044,10 @@ public:
return false; return false;
if (mapPrev.empty()) if (mapPrev.empty())
foreach(const CMerkleTx& tx, vtxPrev) BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
mapPrev[tx.GetHash()] = &tx; mapPrev[tx.GetHash()] = &tx;
foreach(const CTxIn& txin, ptx->vin) BOOST_FOREACH(const CTxIn& txin, ptx->vin)
{ {
if (!mapPrev.count(txin.prevout.hash)) if (!mapPrev.count(txin.prevout.hash))
return false; return false;
@ -1077,7 +1087,7 @@ class CTxIndex
{ {
public: public:
CDiskTxPos pos; CDiskTxPos pos;
vector<CDiskTxPos> vSpent; std::vector<CDiskTxPos> vSpent;
CTxIndex() CTxIndex()
{ {
@ -1149,10 +1159,10 @@ public:
unsigned int nNonce; unsigned int nNonce;
// network and disk // network and disk
vector<CTransaction> vtx; std::vector<CTransaction> vtx;
// memory only // memory only
mutable vector<uint256> vMerkleTree; mutable std::vector<uint256> vMerkleTree;
CBlock() CBlock()
@ -1207,7 +1217,7 @@ public:
int GetSigOpCount() const int GetSigOpCount() const
{ {
int n = 0; int n = 0;
foreach(const CTransaction& tx, vtx) BOOST_FOREACH(const CTransaction& tx, vtx)
n += tx.GetSigOpCount(); n += tx.GetSigOpCount();
return n; return n;
} }
@ -1216,14 +1226,14 @@ public:
uint256 BuildMerkleTree() const uint256 BuildMerkleTree() const
{ {
vMerkleTree.clear(); vMerkleTree.clear();
foreach(const CTransaction& tx, vtx) BOOST_FOREACH(const CTransaction& tx, vtx)
vMerkleTree.push_back(tx.GetHash()); vMerkleTree.push_back(tx.GetHash());
int j = 0; int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{ {
for (int i = 0; i < nSize; i += 2) for (int i = 0; i < nSize; i += 2)
{ {
int i2 = min(i+1, nSize-1); int i2 = std::min(i+1, nSize-1);
vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]), vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2]))); BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
} }
@ -1232,15 +1242,15 @@ public:
return (vMerkleTree.empty() ? 0 : vMerkleTree.back()); return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
} }
vector<uint256> GetMerkleBranch(int nIndex) const std::vector<uint256> GetMerkleBranch(int nIndex) const
{ {
if (vMerkleTree.empty()) if (vMerkleTree.empty())
BuildMerkleTree(); BuildMerkleTree();
vector<uint256> vMerkleBranch; std::vector<uint256> vMerkleBranch;
int j = 0; int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{ {
int i = min(nIndex^1, nSize-1); int i = std::min(nIndex^1, nSize-1);
vMerkleBranch.push_back(vMerkleTree[j+i]); vMerkleBranch.push_back(vMerkleTree[j+i]);
nIndex >>= 1; nIndex >>= 1;
j += nSize; j += nSize;
@ -1248,11 +1258,11 @@ public:
return vMerkleBranch; return vMerkleBranch;
} }
static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex) static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
{ {
if (nIndex == -1) if (nIndex == -1)
return 0; return 0;
foreach(const uint256& otherside, vMerkleBranch) BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
{ {
if (nIndex & 1) if (nIndex & 1)
hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash)); hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
@ -1483,7 +1493,7 @@ public:
for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev) for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
*(--pbegin) = pindex->GetBlockTime(); *(--pbegin) = pindex->GetBlockTime();
sort(pbegin, pend); std::sort(pbegin, pend);
return pbegin[(pend - pbegin)/2]; return pbegin[(pend - pbegin)/2];
} }
@ -1501,7 +1511,7 @@ public:
string ToString() const std::string ToString() const
{ {
return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)", return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
pprev, pnext, nFile, nBlockPos, nHeight, pprev, pnext, nFile, nBlockPos, nHeight,
@ -1570,9 +1580,9 @@ public:
} }
string ToString() const std::string ToString() const
{ {
string str = "CDiskBlockIndex("; std::string str = "CDiskBlockIndex(";
str += CBlockIndex::ToString(); str += CBlockIndex::ToString();
str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)", str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
GetBlockHash().ToString().c_str(), GetBlockHash().ToString().c_str(),
@ -1602,7 +1612,7 @@ public:
class CBlockLocator class CBlockLocator
{ {
protected: protected:
vector<uint256> vHave; std::vector<uint256> vHave;
public: public:
CBlockLocator() CBlockLocator()
@ -1616,7 +1626,7 @@ public:
explicit CBlockLocator(uint256 hashBlock) explicit CBlockLocator(uint256 hashBlock)
{ {
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end()) if (mi != mapBlockIndex.end())
Set((*mi).second); Set((*mi).second);
} }
@ -1660,9 +1670,9 @@ public:
// Retrace how far back it was in the sender's branch // Retrace how far back it was in the sender's branch
int nDistance = 0; int nDistance = 0;
int nStep = 1; int nStep = 1;
foreach(const uint256& hash, vHave) BOOST_FOREACH(const uint256& hash, vHave)
{ {
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end()) if (mi != mapBlockIndex.end())
{ {
CBlockIndex* pindex = (*mi).second; CBlockIndex* pindex = (*mi).second;
@ -1679,9 +1689,9 @@ public:
CBlockIndex* GetBlockIndex() CBlockIndex* GetBlockIndex()
{ {
// Find the first block the caller has in the main chain // Find the first block the caller has in the main chain
foreach(const uint256& hash, vHave) BOOST_FOREACH(const uint256& hash, vHave)
{ {
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end()) if (mi != mapBlockIndex.end())
{ {
CBlockIndex* pindex = (*mi).second; CBlockIndex* pindex = (*mi).second;
@ -1695,9 +1705,9 @@ public:
uint256 GetBlockHash() uint256 GetBlockHash()
{ {
// Find the first block the caller has in the main chain // Find the first block the caller has in the main chain
foreach(const uint256& hash, vHave) BOOST_FOREACH(const uint256& hash, vHave)
{ {
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end()) if (mi != mapBlockIndex.end())
{ {
CBlockIndex* pindex = (*mi).second; CBlockIndex* pindex = (*mi).second;
@ -1731,7 +1741,7 @@ public:
CPrivKey vchPrivKey; CPrivKey vchPrivKey;
int64 nTimeCreated; int64 nTimeCreated;
int64 nTimeExpires; int64 nTimeExpires;
string strComment; std::string strComment;
//// todo: add something to note what created it (user, getnewaddress, change) //// todo: add something to note what created it (user, getnewaddress, change)
//// maybe should have a map<string, string> property map //// maybe should have a map<string, string> property map
@ -1764,7 +1774,7 @@ public:
class CAccount class CAccount
{ {
public: public:
vector<unsigned char> vchPubKey; std::vector<unsigned char> vchPubKey;
CAccount() CAccount()
{ {
@ -1793,11 +1803,11 @@ public:
class CAccountingEntry class CAccountingEntry
{ {
public: public:
string strAccount; std::string strAccount;
int64 nCreditDebit; int64 nCreditDebit;
int64 nTime; int64 nTime;
string strOtherAccount; std::string strOtherAccount;
string strComment; std::string strComment;
CAccountingEntry() CAccountingEntry()
{ {
@ -1848,16 +1858,16 @@ public:
int64 nExpiration; int64 nExpiration;
int nID; int nID;
int nCancel; int nCancel;
set<int> setCancel; std::set<int> setCancel;
int nMinVer; // lowest version inclusive int nMinVer; // lowest version inclusive
int nMaxVer; // highest version inclusive int nMaxVer; // highest version inclusive
set<string> setSubVer; // empty matches all std::set<std::string> setSubVer; // empty matches all
int nPriority; int nPriority;
// Actions // Actions
string strComment; std::string strComment;
string strStatusBar; std::string strStatusBar;
string strReserved; std::string strReserved;
IMPLEMENT_SERIALIZE IMPLEMENT_SERIALIZE
( (
@ -1896,13 +1906,13 @@ public:
strReserved.clear(); strReserved.clear();
} }
string ToString() const std::string ToString() const
{ {
string strSetCancel; std::string strSetCancel;
foreach(int n, setCancel) BOOST_FOREACH(int n, setCancel)
strSetCancel += strprintf("%d ", n); strSetCancel += strprintf("%d ", n);
string strSetSubVer; std::string strSetSubVer;
foreach(string str, setSubVer) BOOST_FOREACH(std::string str, setSubVer)
strSetSubVer += "\"" + str + "\" "; strSetSubVer += "\"" + str + "\" ";
return strprintf( return strprintf(
"CAlert(\n" "CAlert(\n"
@ -1942,8 +1952,8 @@ public:
class CAlert : public CUnsignedAlert class CAlert : public CUnsignedAlert
{ {
public: public:
vector<unsigned char> vchMsg; std::vector<unsigned char> vchMsg;
vector<unsigned char> vchSig; std::vector<unsigned char> vchSig;
CAlert() CAlert()
{ {
@ -1985,7 +1995,7 @@ public:
return (alert.nID <= nCancel || setCancel.count(alert.nID)); return (alert.nID <= nCancel || setCancel.count(alert.nID));
} }
bool AppliesTo(int nVersion, string strSubVerIn) const bool AppliesTo(int nVersion, std::string strSubVerIn) const
{ {
return (IsInEffect() && return (IsInEffect() &&
nMinVer <= nVersion && nVersion <= nMaxVer && nMinVer <= nVersion && nVersion <= nMaxVer &&
@ -2041,11 +2051,13 @@ public:
extern map<uint256, CTransaction> mapTransactions; extern std::map<uint256, CTransaction> mapTransactions;
extern map<uint256, CWalletTx> mapWallet; extern std::map<uint256, CWalletTx> mapWallet;
extern vector<uint256> vWalletUpdated; extern std::vector<uint256> vWalletUpdated;
extern CCriticalSection cs_mapWallet; extern CCriticalSection cs_mapWallet;
extern map<vector<unsigned char>, CPrivKey> mapKeys; extern std::map<std::vector<unsigned char>, CPrivKey> mapKeys;
extern map<uint160, vector<unsigned char> > mapPubKeys; extern std::map<uint160, std::vector<unsigned char> > mapPubKeys;
extern CCriticalSection cs_mapKeys; extern CCriticalSection cs_mapKeys;
extern CKey keyUser; extern CKey keyUser;
#endif

View file

@ -11,6 +11,9 @@
#include <miniupnpc/upnperrors.h> #include <miniupnpc/upnperrors.h>
#endif #endif
using namespace std;
using namespace boost;
static const int MAX_OUTBOUND_CONNECTIONS = 8; static const int MAX_OUTBOUND_CONNECTIONS = 8;
void ThreadMessageHandler2(void* parg); void ThreadMessageHandler2(void* parg);
@ -330,7 +333,7 @@ void ThreadGetMyExternalIP(void* parg)
CAddress addr(addrLocalHost); CAddress addr(addrLocalHost);
addr.nTime = GetAdjustedTime(); addr.nTime = GetAdjustedTime();
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
pnode->PushAddress(addr); pnode->PushAddress(addr);
} }
} }
@ -414,7 +417,7 @@ void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1)
// call this in the destructor so it doesn't get called after it's deleted. // call this in the destructor so it doesn't get called after it's deleted.
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
{ {
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
{ {
CRITICAL_BLOCK(pnode->cs_mapRequests) CRITICAL_BLOCK(pnode->cs_mapRequests)
{ {
@ -451,7 +454,7 @@ bool AnySubscribed(unsigned int nChannel)
if (pnodeLocalHost->IsSubscribed(nChannel)) if (pnodeLocalHost->IsSubscribed(nChannel))
return true; return true;
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->IsSubscribed(nChannel)) if (pnode->IsSubscribed(nChannel))
return true; return true;
return false; return false;
@ -473,7 +476,7 @@ void CNode::Subscribe(unsigned int nChannel, unsigned int nHops)
{ {
// Relay subscribe // Relay subscribe
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode != this) if (pnode != this)
pnode->PushMessage("subscribe", nChannel, nHops); pnode->PushMessage("subscribe", nChannel, nHops);
} }
@ -495,7 +498,7 @@ void CNode::CancelSubscribe(unsigned int nChannel)
{ {
// Relay subscription cancel // Relay subscription cancel
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode != this) if (pnode != this)
pnode->PushMessage("sub-cancel", nChannel); pnode->PushMessage("sub-cancel", nChannel);
} }
@ -513,7 +516,7 @@ CNode* FindNode(unsigned int ip)
{ {
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
{ {
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->addr.ip == ip) if (pnode->addr.ip == ip)
return (pnode); return (pnode);
} }
@ -524,7 +527,7 @@ CNode* FindNode(CAddress addr)
{ {
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
{ {
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->addr == addr) if (pnode->addr == addr)
return (pnode); return (pnode);
} }
@ -661,7 +664,7 @@ void ThreadSocketHandler2(void* parg)
{ {
// Disconnect unused nodes // Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes; vector<CNode*> vNodesCopy = vNodes;
foreach(CNode* pnode, vNodesCopy) BOOST_FOREACH(CNode* pnode, vNodesCopy)
{ {
if (pnode->fDisconnect || if (pnode->fDisconnect ||
(pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty())) (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))
@ -683,7 +686,7 @@ void ThreadSocketHandler2(void* parg)
// Delete disconnected nodes // Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
foreach(CNode* pnode, vNodesDisconnectedCopy) BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
{ {
// wait until threads are done using it // wait until threads are done using it
if (pnode->GetRefCount() <= 0) if (pnode->GetRefCount() <= 0)
@ -729,7 +732,7 @@ void ThreadSocketHandler2(void* parg)
hSocketMax = max(hSocketMax, hListenSocket); hSocketMax = max(hSocketMax, hListenSocket);
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
{ {
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
{ {
if (pnode->hSocket == INVALID_SOCKET || pnode->hSocket < 0) if (pnode->hSocket == INVALID_SOCKET || pnode->hSocket < 0)
continue; continue;
@ -771,7 +774,7 @@ void ThreadSocketHandler2(void* parg)
int nInbound = 0; int nInbound = 0;
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->fInbound) if (pnode->fInbound)
nInbound++; nInbound++;
if (hSocket == INVALID_SOCKET) if (hSocket == INVALID_SOCKET)
@ -801,10 +804,10 @@ void ThreadSocketHandler2(void* parg)
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
{ {
vNodesCopy = vNodes; vNodesCopy = vNodes;
foreach(CNode* pnode, vNodesCopy) BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef(); pnode->AddRef();
} }
foreach(CNode* pnode, vNodesCopy) BOOST_FOREACH(CNode* pnode, vNodesCopy)
{ {
if (fShutdown) if (fShutdown)
return; return;
@ -921,7 +924,7 @@ void ThreadSocketHandler2(void* parg)
} }
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
{ {
foreach(CNode* pnode, vNodesCopy) BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release(); pnode->Release();
} }
@ -1057,7 +1060,7 @@ void DNSAddressSeed()
vector<CAddress> vaddr; vector<CAddress> vaddr;
if (Lookup(strDNSSeed[seed_idx], vaddr, NODE_NETWORK, true)) if (Lookup(strDNSSeed[seed_idx], vaddr, NODE_NETWORK, true))
{ {
foreach (CAddress& addr, vaddr) BOOST_FOREACH (CAddress& addr, vaddr)
{ {
if (addr.GetByte(3) != 127) if (addr.GetByte(3) != 127)
{ {
@ -1148,7 +1151,7 @@ void ThreadOpenConnections2(void* parg)
{ {
for (int64 nLoop = 0;; nLoop++) for (int64 nLoop = 0;; nLoop++)
{ {
foreach(string strAddr, mapMultiArgs["-connect"]) BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
{ {
CAddress addr(strAddr, fAllowDNS); CAddress addr(strAddr, fAllowDNS);
if (addr.IsValid()) if (addr.IsValid())
@ -1166,7 +1169,7 @@ void ThreadOpenConnections2(void* parg)
// Connect to manually added nodes first // Connect to manually added nodes first
if (mapArgs.count("-addnode")) if (mapArgs.count("-addnode"))
{ {
foreach(string strAddr, mapMultiArgs["-addnode"]) BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
{ {
CAddress addr(strAddr, fAllowDNS); CAddress addr(strAddr, fAllowDNS);
if (addr.IsValid()) if (addr.IsValid())
@ -1190,7 +1193,7 @@ void ThreadOpenConnections2(void* parg)
{ {
int nOutbound = 0; int nOutbound = 0;
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
if (!pnode->fInbound) if (!pnode->fInbound)
nOutbound++; nOutbound++;
int nMaxOutboundConnections = MAX_OUTBOUND_CONNECTIONS; int nMaxOutboundConnections = MAX_OUTBOUND_CONNECTIONS;
@ -1233,7 +1236,7 @@ void ThreadOpenConnections2(void* parg)
{ {
nSeedDisconnected = GetTime(); nSeedDisconnected = GetTime();
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
if (setSeed.count(pnode->addr.ip)) if (setSeed.count(pnode->addr.ip))
pnode->fDisconnect = true; pnode->fDisconnect = true;
} }
@ -1241,7 +1244,7 @@ void ThreadOpenConnections2(void* parg)
// Keep setting timestamps to 0 so they won't reconnect // Keep setting timestamps to 0 so they won't reconnect
if (GetTime() - nSeedDisconnected < 60 * 60) if (GetTime() - nSeedDisconnected < 60 * 60)
{ {
foreach(PAIRTYPE(const vector<unsigned char>, CAddress)& item, mapAddresses) BOOST_FOREACH(PAIRTYPE(const vector<unsigned char>, CAddress)& item, mapAddresses)
{ {
if (setSeed.count(item.second.ip) && item.second.nTime != 0) if (setSeed.count(item.second.ip) && item.second.nTime != 0)
{ {
@ -1264,12 +1267,12 @@ void ThreadOpenConnections2(void* parg)
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect. // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
set<unsigned int> setConnected; set<unsigned int> setConnected;
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
setConnected.insert(pnode->addr.ip & 0x0000ffff); setConnected.insert(pnode->addr.ip & 0x0000ffff);
CRITICAL_BLOCK(cs_mapAddresses) CRITICAL_BLOCK(cs_mapAddresses)
{ {
foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses) BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
{ {
const CAddress& addr = item.second; const CAddress& addr = item.second;
if (!addr.IsIPv4() || !addr.IsValid() || setConnected.count(addr.ip & 0x0000ffff)) if (!addr.IsIPv4() || !addr.IsValid() || setConnected.count(addr.ip & 0x0000ffff))
@ -1385,7 +1388,7 @@ void ThreadMessageHandler2(void* parg)
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
{ {
vNodesCopy = vNodes; vNodesCopy = vNodes;
foreach(CNode* pnode, vNodesCopy) BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef(); pnode->AddRef();
} }
@ -1393,7 +1396,7 @@ void ThreadMessageHandler2(void* parg)
CNode* pnodeTrickle = NULL; CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty()) if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())]; pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
foreach(CNode* pnode, vNodesCopy) BOOST_FOREACH(CNode* pnode, vNodesCopy)
{ {
// Receive messages // Receive messages
TRY_CRITICAL_BLOCK(pnode->cs_vRecv) TRY_CRITICAL_BLOCK(pnode->cs_vRecv)
@ -1410,7 +1413,7 @@ void ThreadMessageHandler2(void* parg)
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
{ {
foreach(CNode* pnode, vNodesCopy) BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release(); pnode->Release();
} }
@ -1527,7 +1530,7 @@ void StartNode(void* parg)
{ {
vector<CAddress> vaddr; vector<CAddress> vaddr;
if (Lookup(pszHostName, vaddr, nLocalServices, -1, true)) if (Lookup(pszHostName, vaddr, nLocalServices, -1, true))
foreach (const CAddress &addr, vaddr) BOOST_FOREACH (const CAddress &addr, vaddr)
if (addr.GetByte(3) != 127) if (addr.GetByte(3) != 127)
{ {
addrLocalHost = addr; addrLocalHost = addr;
@ -1648,7 +1651,7 @@ public:
~CNetCleanup() ~CNetCleanup()
{ {
// Close sockets // Close sockets
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->hSocket != INVALID_SOCKET) if (pnode->hSocket != INVALID_SOCKET)
closesocket(pnode->hSocket); closesocket(pnode->hSocket);
if (hListenSocket != INVALID_SOCKET) if (hListenSocket != INVALID_SOCKET)

View file

@ -1,6 +1,16 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying // Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_NET_H
#define BITCOIN_NET_H
#include <deque>
#include <boost/array.hpp>
#include <openssl/rand.h>
#ifndef __WXMSW__
#include <arpa/inet.h>
#endif
class CMessageHeader; class CMessageHeader;
class CAddress; class CAddress;
@ -23,7 +33,7 @@ enum
bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet); bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet);
bool Lookup(const char *pszName, vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false); bool Lookup(const char *pszName, std::vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false); bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
bool GetMyExternalIP(unsigned int& ipRet); bool GetMyExternalIP(unsigned int& ipRet);
bool AddAddress(CAddress addr, int64 nTimePenalty=0); bool AddAddress(CAddress addr, int64 nTimePenalty=0);
@ -34,7 +44,7 @@ void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
bool AnySubscribed(unsigned int nChannel); bool AnySubscribed(unsigned int nChannel);
void MapPort(bool fMapPort); void MapPort(bool fMapPort);
void DNSAddressSeed(); void DNSAddressSeed();
bool BindListenPort(string& strError=REF(string())); bool BindListenPort(std::string& strError=REF(std::string()));
void StartNode(void* parg); void StartNode(void* parg);
bool StopNode(); bool StopNode();
@ -89,12 +99,12 @@ public:
READWRITE(nChecksum); READWRITE(nChecksum);
) )
string GetCommand() std::string GetCommand()
{ {
if (pchCommand[COMMAND_SIZE-1] == 0) if (pchCommand[COMMAND_SIZE-1] == 0)
return string(pchCommand, pchCommand + strlen(pchCommand)); return std::string(pchCommand, pchCommand + strlen(pchCommand));
else else
return string(pchCommand, pchCommand + COMMAND_SIZE); return std::string(pchCommand, pchCommand + COMMAND_SIZE);
} }
bool IsValid() bool IsValid()
@ -182,13 +192,13 @@ public:
Lookup(pszIn, *this, nServicesIn, fNameLookup, 0, true); Lookup(pszIn, *this, nServicesIn, fNameLookup, 0, true);
} }
explicit CAddress(string strIn, int portIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK) explicit CAddress(std::string strIn, int portIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
{ {
Init(); Init();
Lookup(strIn.c_str(), *this, nServicesIn, fNameLookup, portIn); Lookup(strIn.c_str(), *this, nServicesIn, fNameLookup, portIn);
} }
explicit CAddress(string strIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK) explicit CAddress(std::string strIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
{ {
Init(); Init();
Lookup(strIn.c_str(), *this, nServicesIn, fNameLookup, 0, true); Lookup(strIn.c_str(), *this, nServicesIn, fNameLookup, 0, true);
@ -245,16 +255,16 @@ public:
return false; return false;
} }
vector<unsigned char> GetKey() const std::vector<unsigned char> GetKey() const
{ {
CDataStream ss; CDataStream ss;
ss.reserve(18); ss.reserve(18);
ss << FLATDATA(pchReserved) << ip << port; ss << FLATDATA(pchReserved) << ip << port;
#if defined(_MSC_VER) && _MSC_VER < 1300 #if defined(_MSC_VER) && _MSC_VER < 1300
return vector<unsigned char>((unsigned char*)&ss.begin()[0], (unsigned char*)&ss.end()[0]); return std::vector<unsigned char>((unsigned char*)&ss.begin()[0], (unsigned char*)&ss.end()[0]);
#else #else
return vector<unsigned char>(ss.begin(), ss.end()); return std::vector<unsigned char>(ss.begin(), ss.end());
#endif #endif
} }
@ -301,22 +311,22 @@ public:
return ((unsigned char*)&ip)[3-n]; return ((unsigned char*)&ip)[3-n];
} }
string ToStringIPPort() const std::string ToStringIPPort() const
{ {
return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port)); return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
} }
string ToStringIP() const std::string ToStringIP() const
{ {
return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0)); return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
} }
string ToStringPort() const std::string ToStringPort() const
{ {
return strprintf("%u", ntohs(port)); return strprintf("%u", ntohs(port));
} }
string ToString() const std::string ToString() const
{ {
return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port)); return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
} }
@ -364,7 +374,7 @@ public:
hash = hashIn; hash = hashIn;
} }
CInv(const string& strType, const uint256& hashIn) CInv(const std::string& strType, const uint256& hashIn)
{ {
int i; int i;
for (i = 1; i < ARRAYLEN(ppszTypeName); i++) for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
@ -403,7 +413,7 @@ public:
return ppszTypeName[type]; return ppszTypeName[type];
} }
string ToString() const std::string ToString() const
{ {
return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,20).c_str()); return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,20).c_str());
} }
@ -446,17 +456,17 @@ extern uint64 nLocalServices;
extern CAddress addrLocalHost; extern CAddress addrLocalHost;
extern CNode* pnodeLocalHost; extern CNode* pnodeLocalHost;
extern uint64 nLocalHostNonce; extern uint64 nLocalHostNonce;
extern array<int, 10> vnThreadsRunning; extern boost::array<int, 10> vnThreadsRunning;
extern SOCKET hListenSocket; extern SOCKET hListenSocket;
extern vector<CNode*> vNodes; extern std::vector<CNode*> vNodes;
extern CCriticalSection cs_vNodes; extern CCriticalSection cs_vNodes;
extern map<vector<unsigned char>, CAddress> mapAddresses; extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
extern CCriticalSection cs_mapAddresses; extern CCriticalSection cs_mapAddresses;
extern map<CInv, CDataStream> mapRelay; extern std::map<CInv, CDataStream> mapRelay;
extern deque<pair<int64, CInv> > vRelayExpiration; extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
extern CCriticalSection cs_mapRelay; extern CCriticalSection cs_mapRelay;
extern map<CInv, int64> mapAlreadyAskedFor; extern std::map<CInv, int64> mapAlreadyAskedFor;
// Settings // Settings
extern int fUseProxy; extern int fUseProxy;
@ -485,7 +495,7 @@ public:
unsigned int nMessageStart; unsigned int nMessageStart;
CAddress addr; CAddress addr;
int nVersion; int nVersion;
string strSubVer; std::string strSubVer;
bool fClient; bool fClient;
bool fInbound; bool fInbound;
bool fNetworkNode; bool fNetworkNode;
@ -495,7 +505,7 @@ protected:
int nRefCount; int nRefCount;
public: public:
int64 nReleaseTime; int64 nReleaseTime;
map<uint256, CRequestTracker> mapRequests; std::map<uint256, CRequestTracker> mapRequests;
CCriticalSection cs_mapRequests; CCriticalSection cs_mapRequests;
uint256 hashContinue; uint256 hashContinue;
CBlockIndex* pindexLastGetBlocksBegin; CBlockIndex* pindexLastGetBlocksBegin;
@ -503,19 +513,19 @@ public:
int nStartingHeight; int nStartingHeight;
// flood relay // flood relay
vector<CAddress> vAddrToSend; std::vector<CAddress> vAddrToSend;
set<CAddress> setAddrKnown; std::set<CAddress> setAddrKnown;
bool fGetAddr; bool fGetAddr;
set<uint256> setKnown; std::set<uint256> setKnown;
// inventory based relay // inventory based relay
set<CInv> setInventoryKnown; std::set<CInv> setInventoryKnown;
vector<CInv> vInventoryToSend; std::vector<CInv> vInventoryToSend;
CCriticalSection cs_inventory; CCriticalSection cs_inventory;
multimap<int64, CInv> mapAskFor; std::multimap<int64, CInv> mapAskFor;
// publish and subscription // publish and subscription
vector<char> vfSubscribe; std::vector<char> vfSubscribe;
CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false) CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
@ -577,13 +587,13 @@ public:
int GetRefCount() int GetRefCount()
{ {
return max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0); return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
} }
CNode* AddRef(int64 nTimeout=0) CNode* AddRef(int64 nTimeout=0)
{ {
if (nTimeout != 0) if (nTimeout != 0)
nReleaseTime = max(nReleaseTime, GetTime() + nTimeout); nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
else else
nRefCount++; nRefCount++;
return this; return this;
@ -634,11 +644,11 @@ public:
// Make sure not to reuse time indexes to keep things in the same order // Make sure not to reuse time indexes to keep things in the same order
int64 nNow = (GetTime() - 1) * 1000000; int64 nNow = (GetTime() - 1) * 1000000;
static int64 nLastTime; static int64 nLastTime;
nLastTime = nNow = max(nNow, ++nLastTime); nLastTime = nNow = std::max(nNow, ++nLastTime);
// Each retry is 2 minutes after the last // Each retry is 2 minutes after the last
nRequestTime = max(nRequestTime + 2 * 60 * 1000000, nNow); nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
mapAskFor.insert(make_pair(nRequestTime, inv)); mapAskFor.insert(std::make_pair(nRequestTime, inv));
} }
@ -722,7 +732,7 @@ public:
CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost); CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe, PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, string(pszSubVer), nBestHeight); nLocalHostNonce, std::string(pszSubVer), nBestHeight);
} }
@ -948,7 +958,7 @@ inline void RelayInventory(const CInv& inv)
{ {
// Put on lists to offer to the other nodes // Put on lists to offer to the other nodes
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
pnode->PushInventory(inv); pnode->PushInventory(inv);
} }
@ -975,7 +985,7 @@ inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
// Save original serialized message so newer versions are preserved // Save original serialized message so newer versions are preserved
mapRelay[inv] = ss; mapRelay[inv] = ss;
vRelayExpiration.push_back(make_pair(GetTime() + 15 * 60, inv)); vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
} }
RelayInventory(inv); RelayInventory(inv);
@ -1007,7 +1017,7 @@ void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops,
// Relay // Relay
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel))) if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
pnode->PushMessage("publish", nChannel, nHops, obj); pnode->PushMessage("publish", nChannel, nHops, obj);
} }
@ -1018,7 +1028,7 @@ void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops,
uint256 hash = obj.GetHash(); uint256 hash = obj.GetHash();
CRITICAL_BLOCK(cs_vNodes) CRITICAL_BLOCK(cs_vNodes)
foreach(CNode* pnode, vNodes) BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel))) if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
pnode->PushMessage("pub-cancel", nChannel, nHops, hash); pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
@ -1035,3 +1045,5 @@ void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops,
if (obj.setSources.empty()) if (obj.setSources.empty())
AdvertStopPublish(pfrom, nChannel, nHops, obj); AdvertStopPublish(pfrom, nChannel, nHops, obj);
} }
#endif

View file

@ -1,7 +1,10 @@
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying // Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_NOUI_H
#define BITCOIN_NOUI_H
#include <string>
typedef void wxWindow; typedef void wxWindow;
#define wxYES 0x00000002 #define wxYES 0x00000002
@ -31,7 +34,7 @@ typedef void wxWindow;
#define wxMORE 0x00010000 #define wxMORE 0x00010000
#define wxSETUP 0x00020000 #define wxSETUP 0x00020000
inline int MyMessageBox(const string& message, const string& caption="Message", int style=wxOK, wxWindow* parent=NULL, int x=-1, int y=-1) inline int MyMessageBox(const std::string& message, const std::string& caption="Message", int style=wxOK, wxWindow* parent=NULL, int x=-1, int y=-1)
{ {
printf("%s: %s\n", caption.c_str(), message.c_str()); printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
@ -39,17 +42,17 @@ inline int MyMessageBox(const string& message, const string& caption="Message",
} }
#define wxMessageBox MyMessageBox #define wxMessageBox MyMessageBox
inline int ThreadSafeMessageBox(const string& message, const string& caption, int style=wxOK, wxWindow* parent=NULL, int x=-1, int y=-1) inline int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style=wxOK, wxWindow* parent=NULL, int x=-1, int y=-1)
{ {
return MyMessageBox(message, caption, style, parent, x, y); return MyMessageBox(message, caption, style, parent, x, y);
} }
inline bool ThreadSafeAskFee(int64 nFeeRequired, const string& strCaption, wxWindow* parent) inline bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption, wxWindow* parent)
{ {
return true; return true;
} }
inline void CalledSetStatusBar(const string& strText, int nField) inline void CalledSetStatusBar(const std::string& strText, int nField)
{ {
} }
@ -60,3 +63,5 @@ inline void UIThreadCall(boost::function0<void> fn)
inline void MainFrameRepaint() inline void MainFrameRepaint()
{ {
} }
#endif

View file

@ -21,6 +21,8 @@ typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> SSLStream;
// a certain size around 145MB. If we need access to json_spirit outside this // a certain size around 145MB. If we need access to json_spirit outside this
// file, we could use the compiled json_spirit option. // file, we could use the compiled json_spirit option.
using namespace std;
using namespace boost;
using namespace boost::asio; using namespace boost::asio;
using namespace json_spirit; using namespace json_spirit;
@ -81,7 +83,7 @@ void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
entry.push_back(Pair("confirmations", wtx.GetDepthInMainChain())); entry.push_back(Pair("confirmations", wtx.GetDepthInMainChain()));
entry.push_back(Pair("txid", wtx.GetHash().GetHex())); entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime())); entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
foreach(const PAIRTYPE(string,string)& item, wtx.mapValue) BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second)); entry.push_back(Pair(item.first, item.second));
} }
@ -336,7 +338,7 @@ string GetAccountAddress(string strAccount, bool bForceNew=false)
++it) ++it)
{ {
const CWalletTx& wtx = (*it).second; const CWalletTx& wtx = (*it).second;
foreach(const CTxOut& txout, wtx.vout) BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey) if (txout.scriptPubKey == scriptPubKey)
account.vchPubKey.clear(); account.vchPubKey.clear();
} }
@ -449,7 +451,7 @@ Value getaddressesbyaccount(const Array& params, bool fHelp)
Array ret; Array ret;
CRITICAL_BLOCK(cs_mapAddressBook) CRITICAL_BLOCK(cs_mapAddressBook)
{ {
foreach(const PAIRTYPE(string, string)& item, mapAddressBook) BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
{ {
const string& strAddress = item.first; const string& strAddress = item.first;
const string& strName = item.second; const string& strName = item.second;
@ -541,7 +543,7 @@ Value getreceivedbyaddress(const Array& params, bool fHelp)
if (wtx.IsCoinBase() || !wtx.IsFinal()) if (wtx.IsCoinBase() || !wtx.IsFinal())
continue; continue;
foreach(const CTxOut& txout, wtx.vout) BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey) if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth) if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue; nAmount += txout.nValue;
@ -556,7 +558,7 @@ void GetAccountPubKeys(string strAccount, set<CScript>& setPubKey)
{ {
CRITICAL_BLOCK(cs_mapAddressBook) CRITICAL_BLOCK(cs_mapAddressBook)
{ {
foreach(const PAIRTYPE(string, string)& item, mapAddressBook) BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
{ {
const string& strAddress = item.first; const string& strAddress = item.first;
const string& strName = item.second; const string& strName = item.second;
@ -600,7 +602,7 @@ Value getreceivedbyaccount(const Array& params, bool fHelp)
if (wtx.IsCoinBase() || !wtx.IsFinal()) if (wtx.IsCoinBase() || !wtx.IsFinal())
continue; continue;
foreach(const CTxOut& txout, wtx.vout) BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (setPubKey.count(txout.scriptPubKey)) if (setPubKey.count(txout.scriptPubKey))
if (wtx.GetDepthInMainChain() >= nMinDepth) if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue; nAmount += txout.nValue;
@ -678,9 +680,9 @@ Value getbalance(const Array& params, bool fHelp)
list<pair<string, int64> > listSent; list<pair<string, int64> > listSent;
wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount); wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
if (wtx.GetDepthInMainChain() >= nMinDepth) if (wtx.GetDepthInMainChain() >= nMinDepth)
foreach(const PAIRTYPE(string,int64)& r, listReceived) BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
nBalance += r.second; nBalance += r.second;
foreach(const PAIRTYPE(string,int64)& r, listSent) BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listSent)
nBalance -= r.second; nBalance -= r.second;
nBalance -= allFee; nBalance -= allFee;
nBalance += allGeneratedMature; nBalance += allGeneratedMature;
@ -804,7 +806,7 @@ Value sendmany(const Array& params, bool fHelp)
vector<pair<CScript, int64> > vecSend; vector<pair<CScript, int64> > vecSend;
int64 totalAmount = 0; int64 totalAmount = 0;
foreach(const Pair& s, sendTo) BOOST_FOREACH(const Pair& s, sendTo)
{ {
uint160 hash160; uint160 hash160;
string strAddress = s.name_; string strAddress = s.name_;
@ -885,7 +887,7 @@ Value ListReceived(const Array& params, bool fByAccounts)
if (nDepth < nMinDepth) if (nDepth < nMinDepth)
continue; continue;
foreach(const CTxOut& txout, wtx.vout) BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{ {
// Only counting our own bitcoin addresses and not ip addresses // Only counting our own bitcoin addresses and not ip addresses
uint160 hash160 = txout.scriptPubKey.GetBitcoinAddressHash160(); uint160 hash160 = txout.scriptPubKey.GetBitcoinAddressHash160();
@ -904,7 +906,7 @@ Value ListReceived(const Array& params, bool fByAccounts)
map<string, tallyitem> mapAccountTally; map<string, tallyitem> mapAccountTally;
CRITICAL_BLOCK(cs_mapAddressBook) CRITICAL_BLOCK(cs_mapAddressBook)
{ {
foreach(const PAIRTYPE(string, string)& item, mapAddressBook) BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
{ {
const string& strAddress = item.first; const string& strAddress = item.first;
const string& strAccount = item.second; const string& strAccount = item.second;
@ -1024,7 +1026,7 @@ void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDe
// Sent // Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{ {
foreach(const PAIRTYPE(string, int64)& s, listSent) BOOST_FOREACH(const PAIRTYPE(string, int64)& s, listSent)
{ {
Object entry; Object entry;
entry.push_back(Pair("account", strSentAccount)); entry.push_back(Pair("account", strSentAccount));
@ -1042,7 +1044,7 @@ void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDe
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
CRITICAL_BLOCK(cs_mapAddressBook) CRITICAL_BLOCK(cs_mapAddressBook)
{ {
foreach(const PAIRTYPE(string, int64)& r, listReceived) BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)
{ {
string account; string account;
if (mapAddressBook.count(r.first)) if (mapAddressBook.count(r.first))
@ -1114,7 +1116,7 @@ Value listtransactions(const Array& params, bool fHelp)
} }
list<CAccountingEntry> acentries; list<CAccountingEntry> acentries;
walletdb.ListAccountCreditDebit(strAccount, acentries); walletdb.ListAccountCreditDebit(strAccount, acentries);
foreach(CAccountingEntry& entry, acentries) BOOST_FOREACH(CAccountingEntry& entry, acentries)
{ {
txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry))); txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
} }
@ -1162,7 +1164,7 @@ Value listaccounts(const Array& params, bool fHelp)
CRITICAL_BLOCK(cs_mapWallet) CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(cs_mapAddressBook) CRITICAL_BLOCK(cs_mapAddressBook)
{ {
foreach(const PAIRTYPE(string, string)& entry, mapAddressBook) { BOOST_FOREACH(const PAIRTYPE(string, string)& entry, mapAddressBook) {
uint160 hash160; uint160 hash160;
if(AddressToHash160(entry.first, hash160) && mapPubKeys.count(hash160)) // This address belongs to me if(AddressToHash160(entry.first, hash160) && mapPubKeys.count(hash160)) // This address belongs to me
mapAccountBalances[entry.second] = 0; mapAccountBalances[entry.second] = 0;
@ -1177,12 +1179,12 @@ Value listaccounts(const Array& params, bool fHelp)
list<pair<string, int64> > listSent; list<pair<string, int64> > listSent;
wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount); wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
mapAccountBalances[strSentAccount] -= nFee; mapAccountBalances[strSentAccount] -= nFee;
foreach(const PAIRTYPE(string, int64)& s, listSent) BOOST_FOREACH(const PAIRTYPE(string, int64)& s, listSent)
mapAccountBalances[strSentAccount] -= s.second; mapAccountBalances[strSentAccount] -= s.second;
if (wtx.GetDepthInMainChain() >= nMinDepth) if (wtx.GetDepthInMainChain() >= nMinDepth)
{ {
mapAccountBalances[""] += nGeneratedMature; mapAccountBalances[""] += nGeneratedMature;
foreach(const PAIRTYPE(string, int64)& r, listReceived) BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)
if (mapAddressBook.count(r.first)) if (mapAddressBook.count(r.first))
mapAccountBalances[mapAddressBook[r.first]] += r.second; mapAccountBalances[mapAddressBook[r.first]] += r.second;
else else
@ -1193,11 +1195,11 @@ Value listaccounts(const Array& params, bool fHelp)
list<CAccountingEntry> acentries; list<CAccountingEntry> acentries;
CWalletDB().ListAccountCreditDebit("*", acentries); CWalletDB().ListAccountCreditDebit("*", acentries);
foreach(const CAccountingEntry& entry, acentries) BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit; mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret; Object ret;
foreach(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) { BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
} }
return ret; return ret;
@ -1320,7 +1322,7 @@ Value getwork(const Array& params, bool fHelp)
{ {
// Deallocate old blocks since they're obsolete now // Deallocate old blocks since they're obsolete now
mapNewBlock.clear(); mapNewBlock.clear();
foreach(CBlock* pblock, vNewBlock) BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock; delete pblock;
vNewBlock.clear(); vNewBlock.clear();
} }
@ -1490,7 +1492,7 @@ string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeader
<< "Content-Type: application/json\r\n" << "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n" << "Content-Length: " << strMsg.size() << "\r\n"
<< "Accept: application/json\r\n"; << "Accept: application/json\r\n";
foreach(const PAIRTYPE(string, string)& item, mapRequestHeaders) BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n"; s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg; s << "\r\n" << strMsg;
@ -1710,7 +1712,7 @@ bool ClientAllowed(const string& strAddress)
if (strAddress == asio::ip::address_v4::loopback().to_string()) if (strAddress == asio::ip::address_v4::loopback().to_string())
return true; return true;
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"]; const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
foreach(string strAllow, vAllow) BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow)) if (WildcardMatch(strAddress, strAllow))
return true; return true;
return false; return false;

View file

@ -1,9 +1,11 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying // Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "headers.h" #include "headers.h"
using namespace std;
using namespace boost;
bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType); bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
@ -974,7 +976,7 @@ bool Solver(const CScript& scriptPubKey, vector<pair<opcodetype, valtype> >& vSo
// Scan templates // Scan templates
const CScript& script1 = scriptPubKey; const CScript& script1 = scriptPubKey;
foreach(const CScript& script2, vTemplates) BOOST_FOREACH(const CScript& script2, vTemplates)
{ {
vSolutionRet.clear(); vSolutionRet.clear();
opcodetype opcode1, opcode2; opcodetype opcode1, opcode2;
@ -1030,7 +1032,7 @@ bool Solver(const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& s
// Compile solution // Compile solution
CRITICAL_BLOCK(cs_mapKeys) CRITICAL_BLOCK(cs_mapKeys)
{ {
foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution) BOOST_FOREACH(PAIRTYPE(opcodetype, valtype)& item, vSolution)
{ {
if (item.first == OP_PUBKEY) if (item.first == OP_PUBKEY)
{ {
@ -1100,7 +1102,7 @@ bool ExtractPubKey(const CScript& scriptPubKey, bool fMineOnly, vector<unsigned
CRITICAL_BLOCK(cs_mapKeys) CRITICAL_BLOCK(cs_mapKeys)
{ {
foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution) BOOST_FOREACH(PAIRTYPE(opcodetype, valtype)& item, vSolution)
{ {
valtype vchPubKey; valtype vchPubKey;
if (item.first == OP_PUBKEY) if (item.first == OP_PUBKEY)
@ -1133,7 +1135,7 @@ bool ExtractHash160(const CScript& scriptPubKey, uint160& hash160Ret)
if (!Solver(scriptPubKey, vSolution)) if (!Solver(scriptPubKey, vSolution))
return false; return false;
foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution) BOOST_FOREACH(PAIRTYPE(opcodetype, valtype)& item, vSolution)
{ {
if (item.first == OP_PUBKEYHASH) if (item.first == OP_PUBKEYHASH)
{ {

View file

@ -1,6 +1,13 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying // Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef H_BITCOIN_SCRIPT
#define H_BITCOIN_SCRIPT
#include "base58.h"
#include <string>
#include <vector>
class CTransaction; class CTransaction;
@ -310,7 +317,7 @@ inline const char* GetOpName(opcodetype opcode)
inline string ValueString(const vector<unsigned char>& vch) inline std::string ValueString(const std::vector<unsigned char>& vch)
{ {
if (vch.size() <= 4) if (vch.size() <= 4)
return strprintf("%d", CBigNum(vch).getint()); return strprintf("%d", CBigNum(vch).getint());
@ -318,10 +325,10 @@ inline string ValueString(const vector<unsigned char>& vch)
return HexStr(vch); return HexStr(vch);
} }
inline string StackString(const vector<vector<unsigned char> >& vStack) inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
{ {
string str; std::string str;
foreach(const vector<unsigned char>& vch, vStack) BOOST_FOREACH(const std::vector<unsigned char>& vch, vStack)
{ {
if (!str.empty()) if (!str.empty())
str += " "; str += " ";
@ -338,7 +345,7 @@ inline string StackString(const vector<vector<unsigned char> >& vStack)
class CScript : public vector<unsigned char> class CScript : public std::vector<unsigned char>
{ {
protected: protected:
CScript& push_int64(int64 n) CScript& push_int64(int64 n)
@ -371,10 +378,10 @@ protected:
public: public:
CScript() { } CScript() { }
CScript(const CScript& b) : vector<unsigned char>(b.begin(), b.end()) { } CScript(const CScript& b) : std::vector<unsigned char>(b.begin(), b.end()) { }
CScript(const_iterator pbegin, const_iterator pend) : vector<unsigned char>(pbegin, pend) { } CScript(const_iterator pbegin, const_iterator pend) : std::vector<unsigned char>(pbegin, pend) { }
#ifndef _MSC_VER #ifndef _MSC_VER
CScript(const unsigned char* pbegin, const unsigned char* pend) : vector<unsigned char>(pbegin, pend) { } CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
#endif #endif
CScript& operator+=(const CScript& b) CScript& operator+=(const CScript& b)
@ -405,7 +412,7 @@ public:
explicit CScript(opcodetype b) { operator<<(b); } explicit CScript(opcodetype b) { operator<<(b); }
explicit CScript(const uint256& b) { operator<<(b); } explicit CScript(const uint256& b) { operator<<(b); }
explicit CScript(const CBigNum& b) { operator<<(b); } explicit CScript(const CBigNum& b) { operator<<(b); }
explicit CScript(const vector<unsigned char>& b) { operator<<(b); } explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
CScript& operator<<(char b) { return push_int64(b); } CScript& operator<<(char b) { return push_int64(b); }
@ -422,7 +429,7 @@ public:
CScript& operator<<(opcodetype opcode) CScript& operator<<(opcodetype opcode)
{ {
if (opcode < 0 || opcode > 0xff) if (opcode < 0 || opcode > 0xff)
throw runtime_error("CScript::operator<<() : invalid opcode"); throw std::runtime_error("CScript::operator<<() : invalid opcode");
insert(end(), (unsigned char)opcode); insert(end(), (unsigned char)opcode);
return *this; return *this;
} }
@ -447,7 +454,7 @@ public:
return *this; return *this;
} }
CScript& operator<<(const vector<unsigned char>& b) CScript& operator<<(const std::vector<unsigned char>& b)
{ {
if (b.size() < OP_PUSHDATA1) if (b.size() < OP_PUSHDATA1)
{ {
@ -483,7 +490,7 @@ public:
} }
bool GetOp(iterator& pc, opcodetype& opcodeRet, vector<unsigned char>& vchRet) bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
{ {
// Wrapper so it can be called with either iterator or const_iterator // Wrapper so it can be called with either iterator or const_iterator
const_iterator pc2 = pc; const_iterator pc2 = pc;
@ -500,7 +507,7 @@ public:
return fRet; return fRet;
} }
bool GetOp(const_iterator& pc, opcodetype& opcodeRet, vector<unsigned char>& vchRet) const bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
{ {
return GetOp2(pc, opcodeRet, &vchRet); return GetOp2(pc, opcodeRet, &vchRet);
} }
@ -510,7 +517,7 @@ public:
return GetOp2(pc, opcodeRet, NULL); return GetOp2(pc, opcodeRet, NULL);
} }
bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, vector<unsigned char>* pvchRet) const bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
{ {
opcodeRet = OP_INVALIDOPCODE; opcodeRet = OP_INVALIDOPCODE;
if (pvchRet) if (pvchRet)
@ -617,7 +624,7 @@ public:
uint160 GetBitcoinAddressHash160() const uint160 GetBitcoinAddressHash160() const
{ {
opcodetype opcode; opcodetype opcode;
vector<unsigned char> vch; std::vector<unsigned char> vch;
CScript::const_iterator pc = begin(); CScript::const_iterator pc = begin();
if (!GetOp(pc, opcode, vch) || opcode != OP_DUP) return 0; if (!GetOp(pc, opcode, vch) || opcode != OP_DUP) return 0;
if (!GetOp(pc, opcode, vch) || opcode != OP_HASH160) return 0; if (!GetOp(pc, opcode, vch) || opcode != OP_HASH160) return 0;
@ -629,7 +636,7 @@ public:
return hash160; return hash160;
} }
string GetBitcoinAddress() const std::string GetBitcoinAddress() const
{ {
uint160 hash160 = GetBitcoinAddressHash160(); uint160 hash160 = GetBitcoinAddressHash160();
if (hash160 == 0) if (hash160 == 0)
@ -643,12 +650,12 @@ public:
*this << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG; *this << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;
} }
void SetBitcoinAddress(const vector<unsigned char>& vchPubKey) void SetBitcoinAddress(const std::vector<unsigned char>& vchPubKey)
{ {
SetBitcoinAddress(Hash160(vchPubKey)); SetBitcoinAddress(Hash160(vchPubKey));
} }
bool SetBitcoinAddress(const string& strAddress) bool SetBitcoinAddress(const std::string& strAddress)
{ {
this->clear(); this->clear();
uint160 hash160; uint160 hash160;
@ -664,11 +671,11 @@ public:
printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str()); printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
} }
string ToString() const std::string ToString() const
{ {
string str; std::string str;
opcodetype opcode; opcodetype opcode;
vector<unsigned char> vch; std::vector<unsigned char> vch;
const_iterator pc = begin(); const_iterator pc = begin();
while (pc < end()) while (pc < end())
{ {
@ -703,7 +710,9 @@ public:
uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType); uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
bool IsStandard(const CScript& scriptPubKey); bool IsStandard(const CScript& scriptPubKey);
bool IsMine(const CScript& scriptPubKey); bool IsMine(const CScript& scriptPubKey);
bool ExtractPubKey(const CScript& scriptPubKey, bool fMineOnly, vector<unsigned char>& vchPubKeyRet); bool ExtractPubKey(const CScript& scriptPubKey, bool fMineOnly, std::vector<unsigned char>& vchPubKeyRet);
bool ExtractHash160(const CScript& scriptPubKey, uint160& hash160Ret); 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 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); bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, int nHashType=0);
#endif

View file

@ -1,15 +1,23 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying // Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_SERIALIZE_H
#define BITCOIN_SERIALIZE_H
#include <string> #include <string>
#include <vector> #include <vector>
#include <map> #include <map>
#include <set> #include <set>
#include <cassert>
#include <climits>
#include <cstring>
#include <cstdio>
#include <boost/type_traits/is_fundamental.hpp> #include <boost/type_traits/is_fundamental.hpp>
#include <boost/tuple/tuple.hpp> #include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_comparison.hpp> #include <boost/tuple/tuple_comparison.hpp>
#include <boost/tuple/tuple_io.hpp> #include <boost/tuple/tuple_io.hpp>
#if defined(_MSC_VER) || defined(__BORLANDC__) #if defined(_MSC_VER) || defined(__BORLANDC__)
typedef __int64 int64; typedef __int64 int64;
typedef unsigned __int64 uint64; typedef unsigned __int64 uint64;
@ -277,11 +285,11 @@ template<std::size_t LEN>
class CFixedFieldString class CFixedFieldString
{ {
protected: protected:
const string* pcstr; const std::string* pcstr;
string* pstr; std::string* pstr;
public: public:
explicit CFixedFieldString(const string& str) : pcstr(&str), pstr(NULL) { } explicit CFixedFieldString(const std::string& str) : pcstr(&str), pstr(NULL) { }
explicit CFixedFieldString(string& str) : pcstr(&str), pstr(&str) { } explicit CFixedFieldString(std::string& str) : pcstr(&str), pstr(&str) { }
unsigned int GetSerializeSize(int, int=0) const unsigned int GetSerializeSize(int, int=0) const
{ {
@ -317,9 +325,9 @@ public:
// //
// string // string
template<typename C> unsigned int GetSerializeSize(const basic_string<C>& str, int, int=0); template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
template<typename Stream, typename C> void Serialize(Stream& os, const basic_string<C>& str, int, int=0); template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
template<typename Stream, typename C> void Unserialize(Stream& is, basic_string<C>& str, int, int=0); template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
// vector // vector
template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&); template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
@ -398,13 +406,13 @@ inline void Unserialize(Stream& is, T& a, long nType, int nVersion=VERSION)
// string // string
// //
template<typename C> template<typename C>
unsigned int GetSerializeSize(const basic_string<C>& str, int, int) unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
{ {
return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]); return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
} }
template<typename Stream, typename C> template<typename Stream, typename C>
void Serialize(Stream& os, const basic_string<C>& str, int, int) void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
{ {
WriteCompactSize(os, str.size()); WriteCompactSize(os, str.size());
if (!str.empty()) if (!str.empty())
@ -412,7 +420,7 @@ void Serialize(Stream& os, const basic_string<C>& str, int, int)
} }
template<typename Stream, typename C> template<typename Stream, typename C>
void Unserialize(Stream& is, basic_string<C>& str, int, int) void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
{ {
unsigned int nSize = ReadCompactSize(is); unsigned int nSize = ReadCompactSize(is);
str.resize(nSize); str.resize(nSize);
@ -483,7 +491,7 @@ void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion,
unsigned int i = 0; unsigned int i = 0;
while (i < nSize) while (i < nSize)
{ {
unsigned int blk = min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T))); unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
v.resize(i + blk); v.resize(i + blk);
is.read((char*)&v[i], blk * sizeof(T)); is.read((char*)&v[i], blk * sizeof(T));
i += blk; i += blk;
@ -526,19 +534,19 @@ inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersio
// //
inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion) inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
{ {
return GetSerializeSize((const vector<unsigned char>&)v, nType, nVersion); return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
} }
template<typename Stream> template<typename Stream>
void Serialize(Stream& os, const CScript& v, int nType, int nVersion) void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
{ {
Serialize(os, (const vector<unsigned char>&)v, nType, nVersion); Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
} }
template<typename Stream> template<typename Stream>
void Unserialize(Stream& is, CScript& v, int nType, int nVersion) void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
{ {
Unserialize(is, (vector<unsigned char>&)v, nType, nVersion); Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
} }
@ -575,26 +583,26 @@ template<typename T0, typename T1, typename T2>
unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion) unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
{ {
unsigned int nSize = 0; unsigned int nSize = 0;
nSize += GetSerializeSize(get<0>(item), nType, nVersion); nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
nSize += GetSerializeSize(get<1>(item), nType, nVersion); nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
nSize += GetSerializeSize(get<2>(item), nType, nVersion); nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
return nSize; return nSize;
} }
template<typename Stream, typename T0, typename T1, typename T2> template<typename Stream, typename T0, typename T1, typename T2>
void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion) void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
{ {
Serialize(os, get<0>(item), nType, nVersion); Serialize(os, boost::get<0>(item), nType, nVersion);
Serialize(os, get<1>(item), nType, nVersion); Serialize(os, boost::get<1>(item), nType, nVersion);
Serialize(os, get<2>(item), nType, nVersion); Serialize(os, boost::get<2>(item), nType, nVersion);
} }
template<typename Stream, typename T0, typename T1, typename T2> template<typename Stream, typename T0, typename T1, typename T2>
void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion) void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
{ {
Unserialize(is, get<0>(item), nType, nVersion); Unserialize(is, boost::get<0>(item), nType, nVersion);
Unserialize(is, get<1>(item), nType, nVersion); Unserialize(is, boost::get<1>(item), nType, nVersion);
Unserialize(is, get<2>(item), nType, nVersion); Unserialize(is, boost::get<2>(item), nType, nVersion);
} }
@ -606,29 +614,29 @@ template<typename T0, typename T1, typename T2, typename T3>
unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion) unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
{ {
unsigned int nSize = 0; unsigned int nSize = 0;
nSize += GetSerializeSize(get<0>(item), nType, nVersion); nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
nSize += GetSerializeSize(get<1>(item), nType, nVersion); nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
nSize += GetSerializeSize(get<2>(item), nType, nVersion); nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
nSize += GetSerializeSize(get<3>(item), nType, nVersion); nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
return nSize; return nSize;
} }
template<typename Stream, typename T0, typename T1, typename T2, typename T3> template<typename Stream, typename T0, typename T1, typename T2, typename T3>
void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion) void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
{ {
Serialize(os, get<0>(item), nType, nVersion); Serialize(os, boost::get<0>(item), nType, nVersion);
Serialize(os, get<1>(item), nType, nVersion); Serialize(os, boost::get<1>(item), nType, nVersion);
Serialize(os, get<2>(item), nType, nVersion); Serialize(os, boost::get<2>(item), nType, nVersion);
Serialize(os, get<3>(item), nType, nVersion); Serialize(os, boost::get<3>(item), nType, nVersion);
} }
template<typename Stream, typename T0, typename T1, typename T2, typename T3> template<typename Stream, typename T0, typename T1, typename T2, typename T3>
void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion) void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
{ {
Unserialize(is, get<0>(item), nType, nVersion); Unserialize(is, boost::get<0>(item), nType, nVersion);
Unserialize(is, get<1>(item), nType, nVersion); Unserialize(is, boost::get<1>(item), nType, nVersion);
Unserialize(is, get<2>(item), nType, nVersion); Unserialize(is, boost::get<2>(item), nType, nVersion);
Unserialize(is, get<3>(item), nType, nVersion); Unserialize(is, boost::get<3>(item), nType, nVersion);
} }
@ -661,7 +669,7 @@ void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion
typename std::map<K, T, Pred, A>::iterator mi = m.begin(); typename std::map<K, T, Pred, A>::iterator mi = m.begin();
for (unsigned int i = 0; i < nSize; i++) for (unsigned int i = 0; i < nSize; i++)
{ {
pair<K, T> item; std::pair<K, T> item;
Unserialize(is, item, nType, nVersion); Unserialize(is, item, nType, nVersion);
mi = m.insert(mi, item); mi = m.insert(mi, item);
} }
@ -773,7 +781,7 @@ struct secure_allocator : public std::allocator<T>
{ {
if (p != NULL) if (p != NULL)
memset(p, 0, sizeof(T) * n); memset(p, 0, sizeof(T) * n);
allocator<T>::deallocate(p, n); std::allocator<T>::deallocate(p, n);
} }
}; };
@ -787,7 +795,7 @@ struct secure_allocator : public std::allocator<T>
class CDataStream class CDataStream
{ {
protected: protected:
typedef vector<char, secure_allocator<char> > vector_type; typedef std::vector<char, secure_allocator<char> > vector_type;
vector_type vch; vector_type vch;
unsigned int nReadPos; unsigned int nReadPos;
short state; short state;
@ -828,12 +836,12 @@ public:
Init(nTypeIn, nVersionIn); Init(nTypeIn, nVersionIn);
} }
CDataStream(const vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end()) CDataStream(const std::vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
{ {
Init(nTypeIn, nVersionIn); Init(nTypeIn, nVersionIn);
} }
CDataStream(const vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0]) CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
{ {
Init(nTypeIn, nVersionIn); Init(nTypeIn, nVersionIn);
} }
@ -844,7 +852,7 @@ public:
nType = nTypeIn; nType = nTypeIn;
nVersion = nVersionIn; nVersion = nVersionIn;
state = 0; state = 0;
exceptmask = ios::badbit | ios::failbit; exceptmask = std::ios::badbit | std::ios::failbit;
} }
CDataStream& operator+=(const CDataStream& b) CDataStream& operator+=(const CDataStream& b)
@ -860,9 +868,9 @@ public:
return (ret); return (ret);
} }
string str() const std::string str() const
{ {
return (string(begin(), end())); return (std::string(begin(), end()));
} }
@ -895,7 +903,7 @@ public:
vch.insert(it, first, last); vch.insert(it, first, last);
} }
void insert(iterator it, vector<char>::const_iterator first, vector<char>::const_iterator last) void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
{ {
if (it == vch.begin() + nReadPos && last - first <= nReadPos) if (it == vch.begin() + nReadPos && last - first <= nReadPos)
{ {
@ -985,7 +993,7 @@ public:
} }
bool eof() const { return size() == 0; } bool eof() const { return size() == 0; }
bool fail() const { return state & (ios::badbit | ios::failbit); } bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
bool good() const { return !eof() && (state == 0); } bool good() const { return !eof() && (state == 0); }
void clear(short n) { state = n; } // name conflict with vector clear() void clear(short n) { state = n; } // name conflict with vector clear()
short exceptions() { return exceptmask; } short exceptions() { return exceptmask; }
@ -1009,7 +1017,7 @@ public:
{ {
if (nReadPosNext > vch.size()) if (nReadPosNext > vch.size())
{ {
setstate(ios::failbit, "CDataStream::read() : end of data"); setstate(std::ios::failbit, "CDataStream::read() : end of data");
memset(pch, 0, nSize); memset(pch, 0, nSize);
nSize = vch.size() - nReadPos; nSize = vch.size() - nReadPos;
} }
@ -1032,7 +1040,7 @@ public:
{ {
if (nReadPosNext > vch.size()) if (nReadPosNext > vch.size())
{ {
setstate(ios::failbit, "CDataStream::ignore() : end of data"); setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
nSize = vch.size() - nReadPos; nSize = vch.size() - nReadPos;
} }
nReadPos = 0; nReadPos = 0;
@ -1167,7 +1175,7 @@ public:
nType = nTypeIn; nType = nTypeIn;
nVersion = nVersionIn; nVersion = nVersionIn;
state = 0; state = 0;
exceptmask = ios::badbit | ios::failbit; exceptmask = std::ios::badbit | std::ios::failbit;
} }
~CAutoFile() ~CAutoFile()
@ -1201,7 +1209,7 @@ public:
throw std::ios_base::failure(psz); throw std::ios_base::failure(psz);
} }
bool fail() const { return state & (ios::badbit | ios::failbit); } bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
bool good() const { return state == 0; } bool good() const { return state == 0; }
void clear(short n = 0) { state = n; } void clear(short n = 0) { state = n; }
short exceptions() { return exceptmask; } short exceptions() { return exceptmask; }
@ -1219,7 +1227,7 @@ public:
if (!file) if (!file)
throw std::ios_base::failure("CAutoFile::read : file handle is NULL"); throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
if (fread(pch, 1, nSize, file) != nSize) if (fread(pch, 1, nSize, file) != nSize)
setstate(ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed"); setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
return (*this); return (*this);
} }
@ -1228,7 +1236,7 @@ public:
if (!file) if (!file)
throw std::ios_base::failure("CAutoFile::write : file handle is NULL"); throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
if (fwrite(pch, 1, nSize, file) != nSize) if (fwrite(pch, 1, nSize, file) != nSize)
setstate(ios::failbit, "CAutoFile::write : write failed"); setstate(std::ios::failbit, "CAutoFile::write : write failed");
return (*this); return (*this);
} }
@ -1259,3 +1267,5 @@ public:
return (*this); return (*this);
} }
}; };
#endif

View file

@ -13,7 +13,8 @@
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/ */
#ifndef BITCOIN_STRLCPY_H
#define BITCOIN_STRLCPY_H
/* /*
* Copy src to string dst of size siz. At most siz-1 characters * Copy src to string dst of size siz. At most siz-1 characters
* will be copied. Always NUL terminates (unless siz == 0). * will be copied. Always NUL terminates (unless siz == 0).
@ -82,3 +83,4 @@ inline size_t strlcat(char *dst, const char *src, size_t siz)
return(dlen + (s - src)); /* count does not include NUL */ return(dlen + (s - src)); /* count does not include NUL */
} }
#endif

View file

@ -7,6 +7,8 @@
#include <crtdbg.h> #include <crtdbg.h>
#endif #endif
using namespace std;
using namespace boost;
DEFINE_EVENT_TYPE(wxEVT_UITHREADCALL) DEFINE_EVENT_TYPE(wxEVT_UITHREADCALL)
@ -294,7 +296,7 @@ CMainFrame::CMainFrame(wxWindow* parent) : CMainFrameBase(parent)
dResize -= 0.01; dResize -= 0.01;
#endif #endif
wxListCtrl* pplistCtrl[] = {m_listCtrlAll, m_listCtrlSentReceived, m_listCtrlSent, m_listCtrlReceived}; wxListCtrl* pplistCtrl[] = {m_listCtrlAll, m_listCtrlSentReceived, m_listCtrlSent, m_listCtrlReceived};
foreach(wxListCtrl* p, pplistCtrl) BOOST_FOREACH(wxListCtrl* p, pplistCtrl)
{ {
p->InsertColumn(0, "", wxLIST_FORMAT_LEFT, dResize * 0); p->InsertColumn(0, "", wxLIST_FORMAT_LEFT, dResize * 0);
p->InsertColumn(1, "", wxLIST_FORMAT_LEFT, dResize * 0); p->InsertColumn(1, "", wxLIST_FORMAT_LEFT, dResize * 0);
@ -528,7 +530,7 @@ string SingleLine(const string& strIn)
{ {
string strOut; string strOut;
bool fOneSpace = false; bool fOneSpace = false;
foreach(unsigned char c, strIn) BOOST_FOREACH(unsigned char c, strIn)
{ {
if (isspace(c)) if (isspace(c))
{ {
@ -609,7 +611,7 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)
if (nCredit == 0) if (nCredit == 0)
{ {
int64 nUnmatured = 0; int64 nUnmatured = 0;
foreach(const CTxOut& txout, wtx.vout) BOOST_FOREACH(const CTxOut& txout, wtx.vout)
nUnmatured += txout.GetCredit(); nUnmatured += txout.GetCredit();
if (wtx.IsInMainChain()) if (wtx.IsInMainChain())
{ {
@ -644,7 +646,7 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)
// Received by Bitcoin Address // Received by Bitcoin Address
if (!fShowReceived) if (!fShowReceived)
return false; return false;
foreach(const CTxOut& txout, wtx.vout) BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{ {
if (txout.IsMine()) if (txout.IsMine())
{ {
@ -687,11 +689,11 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)
else else
{ {
bool fAllFromMe = true; bool fAllFromMe = true;
foreach(const CTxIn& txin, wtx.vin) BOOST_FOREACH(const CTxIn& txin, wtx.vin)
fAllFromMe = fAllFromMe && txin.IsMine(); fAllFromMe = fAllFromMe && txin.IsMine();
bool fAllToMe = true; bool fAllToMe = true;
foreach(const CTxOut& txout, wtx.vout) BOOST_FOREACH(const CTxOut& txout, wtx.vout)
fAllToMe = fAllToMe && txout.IsMine(); fAllToMe = fAllToMe && txout.IsMine();
if (fAllFromMe && fAllToMe) if (fAllFromMe && fAllToMe)
@ -776,9 +778,9 @@ bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)
// Mixed debit transaction, can't break down payees // Mixed debit transaction, can't break down payees
// //
bool fAllMine = true; bool fAllMine = true;
foreach(const CTxOut& txout, wtx.vout) BOOST_FOREACH(const CTxOut& txout, wtx.vout)
fAllMine = fAllMine && txout.IsMine(); fAllMine = fAllMine && txout.IsMine();
foreach(const CTxIn& txin, wtx.vin) BOOST_FOREACH(const CTxIn& txin, wtx.vin)
fAllMine = fAllMine && txin.IsMine(); fAllMine = fAllMine && txin.IsMine();
InsertLine(fNew, nIndex, hash, strSort, colour, InsertLine(fNew, nIndex, hash, strSort, colour,
@ -1006,7 +1008,7 @@ void CMainFrame::OnPaintListCtrl(wxPaintEvent& event)
string strTop; string strTop;
if (m_listCtrl->GetItemCount()) if (m_listCtrl->GetItemCount())
strTop = (string)m_listCtrl->GetItemText(0); strTop = (string)m_listCtrl->GetItemText(0);
foreach(uint256 hash, vWalletUpdated) BOOST_FOREACH(uint256 hash, vWalletUpdated)
{ {
map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash); map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
if (mi != mapWallet.end()) if (mi != mapWallet.end())
@ -1265,7 +1267,7 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails
if (nNet > 0) if (nNet > 0)
{ {
// Credit // Credit
foreach(const CTxOut& txout, wtx.vout) BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{ {
if (txout.IsMine()) if (txout.IsMine())
{ {
@ -1316,7 +1318,7 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails
// Coinbase // Coinbase
// //
int64 nUnmatured = 0; int64 nUnmatured = 0;
foreach(const CTxOut& txout, wtx.vout) BOOST_FOREACH(const CTxOut& txout, wtx.vout)
nUnmatured += txout.GetCredit(); nUnmatured += txout.GetCredit();
strHTML += _("<b>Credit:</b> "); strHTML += _("<b>Credit:</b> ");
if (wtx.IsInMainChain()) if (wtx.IsInMainChain())
@ -1335,11 +1337,11 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails
else else
{ {
bool fAllFromMe = true; bool fAllFromMe = true;
foreach(const CTxIn& txin, wtx.vin) BOOST_FOREACH(const CTxIn& txin, wtx.vin)
fAllFromMe = fAllFromMe && txin.IsMine(); fAllFromMe = fAllFromMe && txin.IsMine();
bool fAllToMe = true; bool fAllToMe = true;
foreach(const CTxOut& txout, wtx.vout) BOOST_FOREACH(const CTxOut& txout, wtx.vout)
fAllToMe = fAllToMe && txout.IsMine(); fAllToMe = fAllToMe && txout.IsMine();
if (fAllFromMe) if (fAllFromMe)
@ -1347,7 +1349,7 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails
// //
// Debit // Debit
// //
foreach(const CTxOut& txout, wtx.vout) BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{ {
if (txout.IsMine()) if (txout.IsMine())
continue; continue;
@ -1388,10 +1390,10 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails
// //
// Mixed debit transaction // Mixed debit transaction
// //
foreach(const CTxIn& txin, wtx.vin) BOOST_FOREACH(const CTxIn& txin, wtx.vin)
if (txin.IsMine()) if (txin.IsMine())
strHTML += _("<b>Debit:</b> ") + FormatMoney(-txin.GetDebit()) + "<br>"; strHTML += _("<b>Debit:</b> ") + FormatMoney(-txin.GetDebit()) + "<br>";
foreach(const CTxOut& txout, wtx.vout) BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.IsMine()) if (txout.IsMine())
strHTML += _("<b>Credit:</b> ") + FormatMoney(txout.GetCredit()) + "<br>"; strHTML += _("<b>Credit:</b> ") + FormatMoney(txout.GetCredit()) + "<br>";
} }
@ -1418,10 +1420,10 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails
if (fDebug) if (fDebug)
{ {
strHTML += "<hr><br>debug print<br><br>"; strHTML += "<hr><br>debug print<br><br>";
foreach(const CTxIn& txin, wtx.vin) BOOST_FOREACH(const CTxIn& txin, wtx.vin)
if (txin.IsMine()) if (txin.IsMine())
strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>"; strHTML += "<b>Debit:</b> " + FormatMoney(-txin.GetDebit()) + "<br>";
foreach(const CTxOut& txout, wtx.vout) BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.IsMine()) if (txout.IsMine())
strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>"; strHTML += "<b>Credit:</b> " + FormatMoney(txout.GetCredit()) + "<br>";
@ -1431,7 +1433,7 @@ CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetails
strHTML += "<br><b>Inputs:</b><br>"; strHTML += "<br><b>Inputs:</b><br>";
CRITICAL_BLOCK(cs_mapWallet) CRITICAL_BLOCK(cs_mapWallet)
{ {
foreach(const CTxIn& txin, wtx.vin) BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{ {
COutPoint prevout = txin.prevout; COutPoint prevout = txin.prevout;
map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash); map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
@ -2341,7 +2343,7 @@ CAddressBookDialog::CAddressBookDialog(wxWindow* parent, const wxString& strInit
CRITICAL_BLOCK(cs_mapAddressBook) CRITICAL_BLOCK(cs_mapAddressBook)
{ {
string strDefaultReceiving = (string)pframeMain->m_textCtrlAddress->GetValue(); string strDefaultReceiving = (string)pframeMain->m_textCtrlAddress->GetValue();
foreach(const PAIRTYPE(string, string)& item, mapAddressBook) BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapAddressBook)
{ {
string strAddress = item.first; string strAddress = item.first;
string strName = item.second; string strName = item.second;

View file

@ -1,6 +1,8 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying // Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_UI_H
#define BITCOIN_UI_H
DECLARE_EVENT_TYPE(wxEVT_UITHREADCALL, -1) DECLARE_EVENT_TYPE(wxEVT_UITHREADCALL, -1)
@ -12,9 +14,9 @@ extern wxLocale g_locale;
void HandleCtrlA(wxKeyEvent& event); void HandleCtrlA(wxKeyEvent& event);
void UIThreadCall(boost::function0<void>); void UIThreadCall(boost::function0<void>);
int ThreadSafeMessageBox(const string& message, const string& caption="Message", int style=wxOK, wxWindow* parent=NULL, int x=-1, int y=-1); int ThreadSafeMessageBox(const std::string& message, const std::string& caption="Message", int style=wxOK, wxWindow* parent=NULL, int x=-1, int y=-1);
bool ThreadSafeAskFee(int64 nFeeRequired, const string& strCaption, wxWindow* parent); bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption, wxWindow* parent);
void CalledSetStatusBar(const string& strText, int nField); void CalledSetStatusBar(const std::string& strText, int nField);
void MainFrameRepaint(); void MainFrameRepaint();
void CreateMainWindow(); void CreateMainWindow();
void SetStartOnSystemStartup(bool fAutoStart); void SetStartOnSystemStartup(bool fAutoStart);
@ -28,8 +30,8 @@ inline int MyMessageBox(const wxString& message, const wxString& caption="Messag
if (!fDaemon) if (!fDaemon)
return wxMessageBox(message, caption, style, parent, x, y); return wxMessageBox(message, caption, style, parent, x, y);
#endif #endif
printf("wxMessageBox %s: %s\n", string(caption).c_str(), string(message).c_str()); printf("wxMessageBox %s: %s\n", std::string(caption).c_str(), std::string(message).c_str());
fprintf(stderr, "%s: %s\n", string(caption).c_str(), string(message).c_str()); fprintf(stderr, "%s: %s\n", std::string(caption).c_str(), std::string(message).c_str());
return wxOK; return wxOK;
} }
#define wxMessageBox MyMessageBox #define wxMessageBox MyMessageBox
@ -93,8 +95,8 @@ public:
bool fRefresh; bool fRefresh;
void OnUIThreadCall(wxCommandEvent& event); void OnUIThreadCall(wxCommandEvent& event);
int GetSortIndex(const string& strSort); int GetSortIndex(const std::string& strSort);
void InsertLine(bool fNew, int nIndex, uint256 hashKey, string strSort, const wxColour& colour, const wxString& str1, const wxString& str2, const wxString& str3, const wxString& str4, const wxString& str5); void InsertLine(bool fNew, int nIndex, uint256 hashKey, std::string strSort, const wxColour& colour, const wxString& str1, const wxString& str2, const wxString& str3, const wxString& str4, const wxString& str5);
bool DeleteLine(uint256 hashKey); bool DeleteLine(uint256 hashKey);
bool InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex=-1); bool InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex=-1);
void RefreshListCtrl(); void RefreshListCtrl();
@ -176,8 +178,8 @@ public:
// Custom // Custom
bool fEnabledPrev; bool fEnabledPrev;
string strFromSave; std::string strFromSave;
string strMessageSave; std::string strMessageSave;
}; };
@ -211,8 +213,8 @@ public:
void Close(); void Close();
void Repaint(); void Repaint();
bool Status(); bool Status();
bool Status(const string& str); bool Status(const std::string& str);
bool Error(const string& str); bool Error(const std::string& str);
void StartTransfer(); void StartTransfer();
void OnReply2(CDataStream& vRecv); void OnReply2(CDataStream& vRecv);
void OnReply3(CDataStream& vRecv); void OnReply3(CDataStream& vRecv);
@ -257,7 +259,7 @@ public:
wxString GetSelectedAddress(); wxString GetSelectedAddress();
wxString GetSelectedSendingAddress(); wxString GetSelectedSendingAddress();
wxString GetSelectedReceivingAddress(); wxString GetSelectedReceivingAddress();
bool CheckIfMine(const string& strAddress, const string& strTitle); bool CheckIfMine(const std::string& strAddress, const std::string& strTitle);
}; };
@ -281,11 +283,11 @@ protected:
public: public:
/** Constructor */ /** Constructor */
CGetTextFromUserDialog(wxWindow* parent, CGetTextFromUserDialog(wxWindow* parent,
const string& strCaption, const std::string& strCaption,
const string& strMessage1, const std::string& strMessage1,
const string& strValue1="", const std::string& strValue1="",
const string& strMessage2="", const std::string& strMessage2="",
const string& strValue2="") : CGetTextFromUserDialogBase(parent, wxID_ANY, strCaption) const std::string& strValue2="") : CGetTextFromUserDialogBase(parent, wxID_ANY, strCaption)
{ {
int x = GetSize().GetWidth(); int x = GetSize().GetWidth();
int y = GetSize().GetHeight(); int y = GetSize().GetHeight();
@ -308,9 +310,9 @@ public:
} }
// Custom // Custom
string GetValue() { return (string)m_textCtrl1->GetValue(); } std::string GetValue() { return (std::string)m_textCtrl1->GetValue(); }
string GetValue1() { return (string)m_textCtrl1->GetValue(); } std::string GetValue1() { return (std::string)m_textCtrl1->GetValue(); }
string GetValue2() { return (string)m_textCtrl2->GetValue(); } std::string GetValue2() { return (std::string)m_textCtrl2->GetValue(); }
}; };
@ -341,3 +343,5 @@ public:
DECLARE_EVENT_TABLE() DECLARE_EVENT_TABLE()
}; };
#endif

View file

@ -1,9 +1,15 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying // Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_UINT256_H
#define BITCOIN_UINT256_H
#include "serialize.h"
#include <limits.h> #include <limits.h>
#include <string> #include <string>
#include <vector>
#if defined(_MSC_VER) || defined(__BORLANDC__) #if defined(_MSC_VER) || defined(__BORLANDC__)
typedef __int64 int64; typedef __int64 int64;
typedef unsigned __int64 uint64; typedef unsigned __int64 uint64;
@ -16,7 +22,7 @@ typedef unsigned long long uint64;
#endif #endif
inline int Testuint256AdHoc(vector<string> vArg); inline int Testuint256AdHoc(std::vector<std::string> vArg);
@ -296,7 +302,7 @@ public:
char psz[sizeof(pn)*2 + 1]; char psz[sizeof(pn)*2 + 1];
for (int i = 0; i < sizeof(pn); i++) for (int i = 0; i < sizeof(pn); i++)
sprintf(psz + i*2, "%02x", ((unsigned char*)pn)[sizeof(pn) - i - 1]); sprintf(psz + i*2, "%02x", ((unsigned char*)pn)[sizeof(pn) - i - 1]);
return string(psz, psz + sizeof(pn)*2); return std::string(psz, psz + sizeof(pn)*2);
} }
void SetHex(const char* psz) void SetHex(const char* psz)
@ -377,7 +383,7 @@ public:
friend class uint160; friend class uint160;
friend class uint256; friend class uint256;
friend inline int Testuint256AdHoc(vector<string> vArg); friend inline int Testuint256AdHoc(std::vector<std::string> vArg);
}; };
typedef base_uint<160> base_uint160; typedef base_uint<160> base_uint160;
@ -626,7 +632,7 @@ inline const uint256 operator-(const uint256& a, const uint256& b) { return
inline int Testuint256AdHoc(vector<string> vArg) inline int Testuint256AdHoc(std::vector<std::string> vArg)
{ {
uint256 g(0); uint256 g(0);
@ -755,3 +761,5 @@ inline int Testuint256AdHoc(vector<string> vArg)
return (0); return (0);
} }
#endif

View file

@ -1,9 +1,10 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying // Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "headers.h" #include "headers.h"
using namespace std;
using namespace boost;
map<string, string> mapArgs; map<string, string> mapArgs;
map<string, vector<string> > mapMultiArgs; map<string, vector<string> > mapMultiArgs;
@ -704,7 +705,7 @@ void GetDataDir(char* pszDir)
if (!pfMkdir[nVariation]) if (!pfMkdir[nVariation])
{ {
pfMkdir[nVariation] = true; pfMkdir[nVariation] = true;
filesystem::create_directory(pszDir); boost::filesystem::create_directory(pszDir);
} }
} }
@ -855,7 +856,7 @@ void AddTimeData(unsigned int ip, int64 nTime)
{ {
// If nobody has a time different than ours but within 5 minutes of ours, give a warning // If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false; bool fMatch = false;
foreach(int64 nOffset, vTimeOffsets) BOOST_FOREACH(int64 nOffset, vTimeOffsets)
if (nOffset != 0 && abs64(nOffset) < 5 * 60) if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true; fMatch = true;
@ -869,7 +870,7 @@ void AddTimeData(unsigned int ip, int64 nTime)
} }
} }
} }
foreach(int64 n, vTimeOffsets) BOOST_FOREACH(int64 n, vTimeOffsets)
printf("%+"PRI64d" ", n); printf("%+"PRI64d" ", n);
printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60); printf("| nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
} }

View file

@ -1,6 +1,28 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying // Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_UTIL_H
#define BITCOIN_UTIL_H
#include "uint256.h"
#ifndef __WXMSW__
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#endif
#include <map>
#include <vector>
#include <string>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
#include <boost/date_time/gregorian/gregorian_types.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <openssl/sha.h>
#include <openssl/ripemd.h>
#if defined(_MSC_VER) || defined(__BORLANDC__) #if defined(_MSC_VER) || defined(__BORLANDC__)
@ -17,7 +39,6 @@ typedef unsigned long long uint64;
#define __forceinline inline #define __forceinline inline
#endif #endif
#define foreach BOOST_FOREACH
#define loop for (;;) #define loop for (;;)
#define BEGIN(a) ((char*)&(a)) #define BEGIN(a) ((char*)&(a))
#define END(a) ((char*)&((&(a))[1])) #define END(a) ((char*)&((&(a))[1]))
@ -134,8 +155,8 @@ inline const char* _(const char* psz)
extern map<string, string> mapArgs; extern std::map<std::string, std::string> mapArgs;
extern map<string, vector<string> > mapMultiArgs; extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
extern bool fDebug; extern bool fDebug;
extern bool fPrintToConsole; extern bool fPrintToConsole;
extern bool fPrintToDebugger; extern bool fPrintToDebugger;
@ -145,7 +166,7 @@ extern bool fShutdown;
extern bool fDaemon; extern bool fDaemon;
extern bool fServer; extern bool fServer;
extern bool fCommandLine; extern bool fCommandLine;
extern string strMiscWarning; extern std::string strMiscWarning;
extern bool fTestNet; extern bool fTestNet;
extern bool fNoListen; extern bool fNoListen;
extern bool fLogTimestamps; extern bool fLogTimestamps;
@ -154,39 +175,39 @@ void RandAddSeed();
void RandAddSeedPerfmon(); void RandAddSeedPerfmon();
int OutputDebugStringF(const char* pszFormat, ...); int OutputDebugStringF(const char* pszFormat, ...);
int my_snprintf(char* buffer, size_t limit, const char* format, ...); int my_snprintf(char* buffer, size_t limit, const char* format, ...);
string strprintf(const char* format, ...); std::string strprintf(const char* format, ...);
bool error(const char* format, ...); bool error(const char* format, ...);
void LogException(std::exception* pex, const char* pszThread); void LogException(std::exception* pex, const char* pszThread);
void PrintException(std::exception* pex, const char* pszThread); void PrintException(std::exception* pex, const char* pszThread);
void PrintExceptionContinue(std::exception* pex, const char* pszThread); void PrintExceptionContinue(std::exception* pex, const char* pszThread);
void ParseString(const string& str, char c, vector<string>& v); void ParseString(const std::string& str, char c, std::vector<std::string>& v);
string FormatMoney(int64 n, bool fPlus=false); std::string FormatMoney(int64 n, bool fPlus=false);
bool ParseMoney(const string& str, int64& nRet); bool ParseMoney(const std::string& str, int64& nRet);
bool ParseMoney(const char* pszIn, int64& nRet); bool ParseMoney(const char* pszIn, int64& nRet);
vector<unsigned char> ParseHex(const char* psz); std::vector<unsigned char> ParseHex(const char* psz);
vector<unsigned char> ParseHex(const string& str); std::vector<unsigned char> ParseHex(const std::string& str);
void ParseParameters(int argc, char* argv[]); void ParseParameters(int argc, char* argv[]);
const char* wxGetTranslation(const char* psz); const char* wxGetTranslation(const char* psz);
bool WildcardMatch(const char* psz, const char* mask); bool WildcardMatch(const char* psz, const char* mask);
bool WildcardMatch(const string& str, const string& mask); bool WildcardMatch(const std::string& str, const std::string& mask);
int GetFilesize(FILE* file); int GetFilesize(FILE* file);
void GetDataDir(char* pszDirRet); void GetDataDir(char* pszDirRet);
string GetConfigFile(); std::string GetConfigFile();
string GetPidFile(); std::string GetPidFile();
void CreatePidFile(string pidFile, pid_t pid); void CreatePidFile(std::string pidFile, pid_t pid);
void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet); void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
#ifdef __WXMSW__ #ifdef __WXMSW__
string MyGetSpecialFolderPath(int nFolder, bool fCreate); string MyGetSpecialFolderPath(int nFolder, bool fCreate);
#endif #endif
string GetDefaultDataDir(); std::string GetDefaultDataDir();
string GetDataDir(); std::string GetDataDir();
void ShrinkDebugFile(); void ShrinkDebugFile();
int GetRandInt(int nMax); int GetRandInt(int nMax);
uint64 GetRand(uint64 nMax); uint64 GetRand(uint64 nMax);
int64 GetTime(); int64 GetTime();
int64 GetAdjustedTime(); int64 GetAdjustedTime();
void AddTimeData(unsigned int ip, int64 nTime); void AddTimeData(unsigned int ip, int64 nTime);
string FormatFullVersion(); std::string FormatFullVersion();
@ -268,12 +289,12 @@ public:
inline string i64tostr(int64 n) inline std::string i64tostr(int64 n)
{ {
return strprintf("%"PRI64d, n); return strprintf("%"PRI64d, n);
} }
inline string itostr(int n) inline std::string itostr(int n)
{ {
return strprintf("%d", n); return strprintf("%d", n);
} }
@ -287,7 +308,7 @@ inline int64 atoi64(const char* psz)
#endif #endif
} }
inline int64 atoi64(const string& str) inline int64 atoi64(const std::string& str)
{ {
#ifdef _MSC_VER #ifdef _MSC_VER
return _atoi64(str.c_str()); return _atoi64(str.c_str());
@ -296,7 +317,7 @@ inline int64 atoi64(const string& str)
#endif #endif
} }
inline int atoi(const string& str) inline int atoi(const std::string& str)
{ {
return atoi(str.c_str()); return atoi(str.c_str());
} }
@ -317,39 +338,39 @@ inline int64 abs64(int64 n)
} }
template<typename T> template<typename T>
string HexStr(const T itbegin, const T itend, bool fSpaces=false) std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
{ {
if (itbegin == itend) if (itbegin == itend)
return ""; return "";
const unsigned char* pbegin = (const unsigned char*)&itbegin[0]; const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]); const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
string str; std::string str;
str.reserve((pend-pbegin) * (fSpaces ? 3 : 2)); str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
for (const unsigned char* p = pbegin; p != pend; p++) for (const unsigned char* p = pbegin; p != pend; p++)
str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p); str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
return str; return str;
} }
inline string HexStr(const vector<unsigned char>& vch, bool fSpaces=false) inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
{ {
return HexStr(vch.begin(), vch.end(), fSpaces); return HexStr(vch.begin(), vch.end(), fSpaces);
} }
template<typename T> template<typename T>
string HexNumStr(const T itbegin, const T itend, bool f0x=true) std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
{ {
if (itbegin == itend) if (itbegin == itend)
return ""; return "";
const unsigned char* pbegin = (const unsigned char*)&itbegin[0]; const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]); const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
string str = (f0x ? "0x" : ""); std::string str = (f0x ? "0x" : "");
str.reserve(str.size() + (pend-pbegin) * 2); str.reserve(str.size() + (pend-pbegin) * 2);
for (const unsigned char* p = pend-1; p >= pbegin; p--) for (const unsigned char* p = pend-1; p >= pbegin; p--)
str += strprintf("%02x", *p); str += strprintf("%02x", *p);
return str; return str;
} }
inline string HexNumStr(const vector<unsigned char>& vch, bool f0x=true) inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
{ {
return HexNumStr(vch.begin(), vch.end(), f0x); return HexNumStr(vch.begin(), vch.end(), f0x);
} }
@ -360,7 +381,7 @@ void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSp
printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str()); printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
} }
inline void PrintHex(const vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true) inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
{ {
printf(pszFormat, HexStr(vch, fSpaces).c_str()); printf(pszFormat, HexStr(vch, fSpaces).c_str());
} }
@ -380,11 +401,11 @@ inline int64 GetPerformanceCounter()
inline int64 GetTimeMillis() inline int64 GetTimeMillis()
{ {
return (posix_time::ptime(posix_time::microsec_clock::universal_time()) - return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
posix_time::ptime(gregorian::date(1970,1,1))).total_milliseconds(); boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
} }
inline string DateTimeStrFormat(const char* pszFormat, int64 nTime) inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
{ {
time_t n = nTime; time_t n = nTime;
struct tm* ptmTime = gmtime(&n); struct tm* ptmTime = gmtime(&n);
@ -409,21 +430,21 @@ inline bool IsSwitchChar(char c)
#endif #endif
} }
inline string GetArg(const string& strArg, const string& strDefault) inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
{ {
if (mapArgs.count(strArg)) if (mapArgs.count(strArg))
return mapArgs[strArg]; return mapArgs[strArg];
return strDefault; return strDefault;
} }
inline int64 GetArg(const string& strArg, int64 nDefault) inline int64 GetArg(const std::string& strArg, int64 nDefault)
{ {
if (mapArgs.count(strArg)) if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]); return atoi64(mapArgs[strArg]);
return nDefault; return nDefault;
} }
inline bool GetBoolArg(const string& strArg) inline bool GetBoolArg(const std::string& strArg)
{ {
if (mapArgs.count(strArg)) if (mapArgs.count(strArg))
{ {
@ -538,7 +559,7 @@ uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
return Hash(ss.begin(), ss.end()); return Hash(ss.begin(), ss.end());
} }
inline uint160 Hash160(const vector<unsigned char>& vch) inline uint160 Hash160(const std::vector<unsigned char>& vch)
{ {
uint256 hash1; uint256 hash1;
SHA256(&vch[0], vch.size(), (unsigned char*)&hash1); SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
@ -655,3 +676,5 @@ inline bool AffinityBugWorkaround(void(*pfn)(void*))
#endif #endif
return false; return false;
} }
#endif