Page MenuHomePhabricator

No OneTemporary

diff --git a/src/rpc.cpp b/src/rpc.cpp
index 780209920..6f951b743 100644
--- a/src/rpc.cpp
+++ b/src/rpc.cpp
@@ -1,2221 +1,2226 @@
// Copyright (c) 2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "headers.h"
#include "cryptopp/sha.h"
#include "db.h"
#include "net.h"
#include "init.h"
#undef printf
#include <boost/asio.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#ifdef USE_SSL
#include <boost/asio/ssl.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> SSLStream;
#endif
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_writer_template.h"
#include "json/json_spirit_utils.h"
#define printf OutputDebugStringF
// MinGW 3.4.5 gets "fatal error: had to relocate PCH" if the json headers are
// precompiled in headers.h. The problem might be when the pch file goes over
// a certain size around 145MB. If we need access to json_spirit outside this
// file, we could use the compiled json_spirit option.
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
void ThreadRPCServer2(void* parg);
typedef Value(*rpcfn_type)(const Array& params, bool fHelp);
extern map<string, rpcfn_type> mapCallTable;
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void PrintConsole(const char* format, ...)
{
char buffer[50000];
int limit = sizeof(buffer);
va_list arg_ptr;
va_start(arg_ptr, format);
int ret = _vsnprintf(buffer, limit, format, arg_ptr);
va_end(arg_ptr);
if (ret < 0 || ret >= limit)
{
ret = limit - 1;
buffer[limit-1] = 0;
}
printf("%s", buffer);
#if defined(__WXMSW__) && defined(GUI)
MyMessageBox(buffer, "Bitcoin", wxOK | wxICON_EXCLAMATION);
#else
fprintf(stdout, "%s", buffer);
#endif
}
int64 AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > 21000000.0)
throw JSONRPCError(-3, "Invalid amount");
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(-3, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
entry.push_back(Pair("confirmations", wtx.GetDepthInMainChain()));
entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const Value& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(-11, "Invalid account name");
return strAccount;
}
///
/// Note: This interface may still be subject to change.
///
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
string strRet;
set<rpcfn_type> setDone;
for (map<string, rpcfn_type>::iterator mi = mapCallTable.begin(); mi != mapCallTable.end(); ++mi)
{
string strMethod = (*mi).first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod == "getamountreceived" ||
strMethod == "getallreceived" ||
(strMethod.find("label") != string::npos))
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
try
{
Array params;
rpcfn_type pfn = (*mi).second;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != -1)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value stop(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"stop\n"
"Stop bitcoin server.");
// Shutdown will take long enough that the response should get back
CreateThread(Shutdown, NULL);
return "bitcoin server stopping";
}
Value getblockcount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockcount\n"
"Returns the number of blocks in the longest block chain.");
return nBestHeight;
}
Value getblocknumber(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblocknumber\n"
"Returns the block number of the latest block in the longest block chain.");
return nBestHeight;
}
Value getconnectioncount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getconnectioncount\n"
"Returns the number of connections to other nodes.");
return (int)vNodes.size();
}
double GetDifficulty()
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (pindexBest == NULL)
return 1.0;
int nShift = (pindexBest->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(pindexBest->nBits & 0x00ffffff);
while (nShift < 29)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > 29)
{
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
Value getdifficulty(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getdifficulty\n"
"Returns the proof-of-work difficulty as a multiple of the minimum difficulty.");
return GetDifficulty();
}
Value getgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getgenerate\n"
"Returns true or false.");
return (bool)fGenerateBitcoins;
}
Value setgenerate(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setgenerate <generate> [genproclimit]\n"
"<generate> is true or false to turn generation on or off.\n"
"Generation is limited to [genproclimit] processors, -1 is unlimited.");
bool fGenerate = true;
if (params.size() > 0)
fGenerate = params[0].get_bool();
if (params.size() > 1)
{
int nGenProcLimit = params[1].get_int();
fLimitProcessors = (nGenProcLimit != -1);
WriteSetting("fLimitProcessors", fLimitProcessors);
if (nGenProcLimit != -1)
WriteSetting("nLimitProcessors", nLimitProcessors = nGenProcLimit);
if (nGenProcLimit == 0)
fGenerate = false;
}
GenerateBitcoins(fGenerate, pwalletMain);
return Value::null;
}
Value gethashespersec(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"gethashespersec\n"
"Returns a recent hashes per second performance measurement while generating.");
if (GetTimeMillis() - nHPSTimerStart > 8000)
return (boost::int64_t)0;
return (boost::int64_t)dHashesPerSec;
}
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
Object obj;
obj.push_back(Pair("version", (int)VERSION));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (fUseProxy ? addrProxy.ToStringIPPort() : string())));
obj.push_back(Pair("generate", (bool)fGenerateBitcoins));
obj.push_back(Pair("genproclimit", (int)(fLimitProcessors ? nLimitProcessors : -1)));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
obj.push_back(Pair("testnet", fTestNet));
obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress [account]\n"
"Returns a new bitcoin address for receiving payments. "
"If [account] is specified (recommended), it is added to the address book "
"so payments received with the address will be credited to [account].");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
// Generate a new key that is added to wallet
string strAddress = PubKeyToAddress(pwalletMain->GetKeyFromKeyPool());
- pwalletMain->SetAddressBookName(strAddress, strAccount);
+ // This could be done in the same main CS as GetKeyFromKeyPool.
+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
+ pwalletMain->SetAddressBookName(strAddress, strAccount);
+
return strAddress;
}
-// requires cs_main, cs_mapWallet locks
+// requires cs_main, cs_mapWallet, cs_mapAddressBook locks
string GetAccountAddress(string strAccount, bool bForceNew=false)
{
string strAddress;
CWalletDB walletdb(pwalletMain->strWalletFile);
walletdb.TxnBegin();
CAccount account;
walletdb.ReadAccount(strAccount, account);
// Check if the current key has been used
if (!account.vchPubKey.empty())
{
CScript scriptPubKey;
scriptPubKey.SetBitcoinAddress(account.vchPubKey);
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && !account.vchPubKey.empty();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
account.vchPubKey.clear();
}
}
// Generate a new key
if (account.vchPubKey.empty() || bForceNew)
{
account.vchPubKey = pwalletMain->GetKeyFromKeyPool();
string strAddress = PubKeyToAddress(account.vchPubKey);
pwalletMain->SetAddressBookName(strAddress, strAccount);
walletdb.WriteAccount(strAccount, account);
}
walletdb.TxnCommit();
strAddress = PubKeyToAddress(account.vchPubKey);
return strAddress;
}
Value getaccountaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress <account>\n"
"Returns the current bitcoin address for receiving payments to this account.");
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
Value ret;
CRITICAL_BLOCK(cs_main)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
ret = GetAccountAddress(strAccount);
}
return ret;
}
Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount <bitcoinaddress> <account>\n"
"Sets the account associated with the given address.");
string strAddress = params[0].get_str();
uint160 hash160;
bool isValid = AddressToHash160(strAddress, hash160);
if (!isValid)
throw JSONRPCError(-5, "Invalid bitcoin address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Detect when changing the account of an address that is the 'unused current key' of another account:
CRITICAL_BLOCK(cs_main)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
if (pwalletMain->mapAddressBook.count(strAddress))
{
string strOldAccount = pwalletMain->mapAddressBook[strAddress];
if (strAddress == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
+
+ pwalletMain->SetAddressBookName(strAddress, strAccount);
}
- pwalletMain->SetAddressBookName(strAddress, strAccount);
return Value::null;
}
Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount <bitcoinaddress>\n"
"Returns the account associated with the given address.");
string strAddress = params[0].get_str();
string strAccount;
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
map<string, string>::iterator mi = pwalletMain->mapAddressBook.find(strAddress);
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
strAccount = (*mi).second;
}
return strAccount;
}
Value getaddressesbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount <account>\n"
"Returns the list of addresses for the given account.");
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
Array ret;
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
BOOST_FOREACH(const PAIRTYPE(string, string)& item, pwalletMain->mapAddressBook)
{
const string& strAddress = item.first;
const string& strName = item.second;
if (strName == strAccount)
{
// We're only adding valid bitcoin addresses and not ip addresses
CScript scriptPubKey;
if (scriptPubKey.SetBitcoinAddress(strAddress))
ret.push_back(strAddress);
}
}
}
return ret;
}
Value settxfee(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"settxfee <amount>\n"
"<amount> is a real and is rounded to the nearest 0.00000001");
// Amount
int64 nAmount = 0;
if (params[0].get_real() != 0.0)
nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
nTransactionFee = nAmount;
return true;
}
Value sendtoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress <bitcoinaddress> <amount> [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001");
string strAddress = params[0].get_str();
// Amount
int64 nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
CRITICAL_BLOCK(cs_main)
{
string strError = pwalletMain->SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
if (strError != "")
throw JSONRPCError(-4, strError);
}
return wtx.GetHash().GetHex();
}
Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress <bitcoinaddress> [minconf=1]\n"
"Returns the total amount received by <bitcoinaddress> in transactions with at least [minconf] confirmations.");
// Bitcoin address
string strAddress = params[0].get_str();
CScript scriptPubKey;
if (!scriptPubKey.SetBitcoinAddress(strAddress))
throw JSONRPCError(-5, "Invalid bitcoin address");
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
int64 nAmount = 0;
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return ValueFromAmount(nAmount);
}
void GetAccountPubKeys(string strAccount, set<CScript>& setPubKey)
{
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
BOOST_FOREACH(const PAIRTYPE(string, string)& item, pwalletMain->mapAddressBook)
{
const string& strAddress = item.first;
const string& strName = item.second;
if (strName == strAccount)
{
// We're only counting our own valid bitcoin addresses and not ip addresses
CScript scriptPubKey;
if (scriptPubKey.SetBitcoinAddress(strAddress))
if (IsMine(*pwalletMain,scriptPubKey))
setPubKey.insert(scriptPubKey);
}
}
}
}
Value getreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount <account> [minconf=1]\n"
"Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys that have the label
string strAccount = AccountFromValue(params[0]);
set<CScript> setPubKey;
GetAccountPubKeys(strAccount, setPubKey);
// Tally
int64 nAmount = 0;
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (setPubKey.count(txout.scriptPubKey))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
{
int64 nBalance = 0;
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal())
continue;
int64 nGenerated, nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nGenerated, nReceived, nSent, nFee);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
nBalance += nReceived;
nBalance += nGenerated - nSent - nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
}
return nBalance;
}
int64 GetAccountBalance(const string& strAccount, int nMinDepth)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth);
}
Value getbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 0 || params.size() > 2)
throw runtime_error(
"getbalance [account] [minconf=1]\n"
"If [account] is not specified, returns the server's total available balance.\n"
"If [account] is specified, returns the balance in the account.");
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and getbalance '*' should always return the same number.
int64 nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal())
continue;
int64 allGeneratedImmature, allGeneratedMature, allFee;
allGeneratedImmature = allGeneratedMature = allFee = 0;
string strSentAccount;
list<pair<string, int64> > listReceived;
list<pair<string, int64> > listSent;
wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
if (wtx.GetDepthInMainChain() >= nMinDepth)
BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
nBalance += r.second;
BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listSent)
nBalance -= r.second;
nBalance -= allFee;
nBalance += allGeneratedMature;
}
return ValueFromAmount(nBalance);
}
string strAccount = AccountFromValue(params[0]);
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
return ValueFromAmount(nBalance);
}
Value movecmd(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
"Move from one account in your wallet to another.");
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
int64 nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
walletdb.TxnBegin();
int64 nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
walletdb.TxnCommit();
}
return true;
}
Value sendfrom(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom <fromaccount> <tobitcoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001");
string strAccount = AccountFromValue(params[0]);
string strAddress = params[1].get_str();
int64 nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
CRITICAL_BLOCK(cs_main)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (nAmount > nBalance)
throw JSONRPCError(-6, "Account has insufficient funds");
// Send
string strError = pwalletMain->SendMoneyToBitcoinAddress(strAddress, nAmount, wtx);
if (strError != "")
throw JSONRPCError(-4, strError);
}
return wtx.GetHash().GetHex();
}
Value sendmany(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
"amounts are double-precision floating point numbers");
string strAccount = AccountFromValue(params[0]);
Object sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<string> setAddress;
vector<pair<CScript, int64> > vecSend;
int64 totalAmount = 0;
BOOST_FOREACH(const Pair& s, sendTo)
{
uint160 hash160;
string strAddress = s.name_;
if (setAddress.count(strAddress))
throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+strAddress);
setAddress.insert(strAddress);
CScript scriptPubKey;
if (!scriptPubKey.SetBitcoinAddress(strAddress))
throw JSONRPCError(-5, string("Invalid bitcoin address:")+strAddress);
int64 nAmount = AmountFromValue(s.value_);
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
CRITICAL_BLOCK(cs_main)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (totalAmount > nBalance)
throw JSONRPCError(-6, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
int64 nFeeRequired = 0;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
if (!fCreated)
{
if (totalAmount + nFeeRequired > pwalletMain->GetBalance())
throw JSONRPCError(-6, "Insufficient funds");
throw JSONRPCError(-4, "Transaction creation failed");
}
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(-4, "Transaction commit failed");
}
return wtx.GetHash().GetHex();
}
struct tallyitem
{
int64 nAmount;
int nConf;
tallyitem()
{
nAmount = 0;
nConf = INT_MAX;
}
};
Value ListReceived(const Array& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
// Tally
map<uint160, tallyitem> mapTally;
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !wtx.IsFinal())
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
// Only counting our own bitcoin addresses and not ip addresses
uint160 hash160 = txout.scriptPubKey.GetBitcoinAddressHash160();
if (hash160 == 0 || !mapPubKeys.count(hash160)) // IsMine
continue;
tallyitem& item = mapTally[hash160];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
}
}
}
// Reply
Array ret;
map<string, tallyitem> mapAccountTally;
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
BOOST_FOREACH(const PAIRTYPE(string, string)& item, pwalletMain->mapAddressBook)
{
const string& strAddress = item.first;
const string& strAccount = item.second;
uint160 hash160;
if (!AddressToHash160(strAddress, hash160))
continue;
map<uint160, tallyitem>::iterator it = mapTally.find(hash160);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
int64 nAmount = 0;
int nConf = INT_MAX;
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
}
else
{
Object obj;
obj.push_back(Pair("address", strAddress));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("label", strAccount)); // deprecated
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
ret.push_back(obj);
}
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
int64 nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
Object obj;
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("label", (*it).first)); // deprecated
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == INT_MAX ? 0 : nConf)));
ret.push_back(obj);
}
}
return ret;
}
Value listreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaddress [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include addresses that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"address\" : receiving address\n"
" \"account\" : the account of the receiving address\n"
" \"amount\" : total amount received by the address\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, false);
}
Value listreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaccount [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include accounts that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"account\" : the account of the receiving addresses\n"
" \"amount\" : total amount received by addresses with this account\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, true);
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
{
int64 nGeneratedImmature, nGeneratedMature, nFee;
string strSentAccount;
list<pair<string, int64> > listReceived;
list<pair<string, int64> > listSent;
wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
bool fAllAccounts = (strAccount == string("*"));
// Generated blocks assigned to account ""
if ((nGeneratedMature+nGeneratedImmature) != 0 && (fAllAccounts || strAccount == ""))
{
Object entry;
entry.push_back(Pair("account", string("")));
if (nGeneratedImmature)
{
entry.push_back(Pair("category", wtx.GetDepthInMainChain() ? "immature" : "orphan"));
entry.push_back(Pair("amount", ValueFromAmount(nGeneratedImmature)));
}
else
{
entry.push_back(Pair("category", "generate"));
entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature)));
}
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const PAIRTYPE(string, int64)& s, listSent)
{
Object entry;
entry.push_back(Pair("account", strSentAccount));
entry.push_back(Pair("address", s.first));
entry.push_back(Pair("category", "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.first))
account = pwalletMain->mapAddressBook[r.first];
if (fAllAccounts || (account == strAccount))
{
Object entry;
entry.push_back(Pair("account", account));
entry.push_back(Pair("address", r.first));
entry.push_back(Pair("category", "receive"));
entry.push_back(Pair("amount", ValueFromAmount(r.second)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
Object entry;
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
Value listtransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listtransactions [account] [count=10] [from=0]\n"
"Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
Array ret;
CWalletDB walletdb(pwalletMain->strWalletFile);
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
// Firs: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap:
typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef multimap<int64, TxPair > TxItems;
TxItems txByTime;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
CWalletTx* wtx = &((*it).second);
txByTime.insert(make_pair(wtx->GetTxTime(), TxPair(wtx, (CAccountingEntry*)0)));
}
list<CAccountingEntry> acentries;
walletdb.ListAccountCreditDebit(strAccount, acentries);
BOOST_FOREACH(CAccountingEntry& entry, acentries)
{
txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
}
// Now: iterate backwards until we have nCount items to return:
TxItems::reverse_iterator it = txByTime.rbegin();
for (std::advance(it, nFrom); it != txByTime.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if (ret.size() >= nCount) break;
}
// ret is now newest to oldest
}
// Make sure we return only last nCount items (sends-to-self might give us an extra):
if (ret.size() > nCount)
{
Array::iterator last = ret.begin();
std::advance(last, nCount);
ret.erase(last, ret.end());
}
std::reverse(ret.begin(), ret.end()); // oldest to newest
return ret;
}
Value listaccounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"listaccounts [minconf=1]\n"
"Returns Object that has account names as keys, account balances as values.");
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
map<string, int64> mapAccountBalances;
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
BOOST_FOREACH(const PAIRTYPE(string, string)& entry, pwalletMain->mapAddressBook) {
uint160 hash160;
if(AddressToHash160(entry.first, hash160) && mapPubKeys.count(hash160)) // This address belongs to me
mapAccountBalances[entry.second] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
int64 nGeneratedImmature, nGeneratedMature, nFee;
string strSentAccount;
list<pair<string, int64> > listReceived;
list<pair<string, int64> > listSent;
wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const PAIRTYPE(string, int64)& s, listSent)
mapAccountBalances[strSentAccount] -= s.second;
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
mapAccountBalances[""] += nGeneratedMature;
BOOST_FOREACH(const PAIRTYPE(string, int64)& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.first))
mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
else
mapAccountBalances[""] += r.second;
}
}
}
list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret;
BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
Value gettransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"gettransaction <txid>\n"
"Get detailed information about <txid>");
uint256 hash;
hash.SetHex(params[0].get_str());
Object entry;
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(-5, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
int64 nCredit = wtx.GetCredit();
int64 nDebit = wtx.GetDebit();
int64 nNet = nCredit - nDebit;
int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe())
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(pwalletMain->mapWallet[hash], entry);
Array details;
ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details);
entry.push_back(Pair("details", details));
}
return entry;
}
Value backupwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet <destination>\n"
"Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
string strDest = params[0].get_str();
BackupWallet(*pwalletMain, strDest);
return Value::null;
}
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <bitcoinaddress>\n"
"Return information about <bitcoinaddress>.");
string strAddress = params[0].get_str();
uint160 hash160;
bool isValid = AddressToHash160(strAddress, hash160);
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
// Call Hash160ToAddress() so we always return current ADDRESSVERSION
// version of the address:
string currentAddress = Hash160ToAddress(hash160);
ret.push_back(Pair("address", currentAddress));
ret.push_back(Pair("ismine", (mapPubKeys.count(hash160) > 0)));
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
if (pwalletMain->mapAddressBook.count(currentAddress))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[currentAddress]));
}
}
return ret;
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data\n"
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash\n"
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(-9, "Bitcoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "Bitcoin is downloading blocks...");
static map<uint256, pair<CBlock*, unsigned int> > mapNewBlock;
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
nTransactionsUpdatedLast = nTransactionsUpdated;
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(reservekey);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
vNewBlock.push_back(pblock);
}
// Update nTime
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
static int64 nPrevTime = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, nPrevTime);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, nExtraNonce);
// Prebuild hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate))));
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1))));
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(-8, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = CryptoPP::ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
unsigned int nExtraNonce = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
//
// Call Table
//
pair<string, rpcfn_type> pCallTable[] =
{
make_pair("help", &help),
make_pair("stop", &stop),
make_pair("getblockcount", &getblockcount),
make_pair("getblocknumber", &getblocknumber),
make_pair("getconnectioncount", &getconnectioncount),
make_pair("getdifficulty", &getdifficulty),
make_pair("getgenerate", &getgenerate),
make_pair("setgenerate", &setgenerate),
make_pair("gethashespersec", &gethashespersec),
make_pair("getinfo", &getinfo),
make_pair("getnewaddress", &getnewaddress),
make_pair("getaccountaddress", &getaccountaddress),
make_pair("setaccount", &setaccount),
make_pair("setlabel", &setaccount), // deprecated
make_pair("getaccount", &getaccount),
make_pair("getlabel", &getaccount), // deprecated
make_pair("getaddressesbyaccount", &getaddressesbyaccount),
make_pair("getaddressesbylabel", &getaddressesbyaccount), // deprecated
make_pair("sendtoaddress", &sendtoaddress),
make_pair("getamountreceived", &getreceivedbyaddress), // deprecated, renamed to getreceivedbyaddress
make_pair("getallreceived", &listreceivedbyaddress), // deprecated, renamed to listreceivedbyaddress
make_pair("getreceivedbyaddress", &getreceivedbyaddress),
make_pair("getreceivedbyaccount", &getreceivedbyaccount),
make_pair("getreceivedbylabel", &getreceivedbyaccount), // deprecated
make_pair("listreceivedbyaddress", &listreceivedbyaddress),
make_pair("listreceivedbyaccount", &listreceivedbyaccount),
make_pair("listreceivedbylabel", &listreceivedbyaccount), // deprecated
make_pair("backupwallet", &backupwallet),
make_pair("validateaddress", &validateaddress),
make_pair("getbalance", &getbalance),
make_pair("move", &movecmd),
make_pair("sendfrom", &sendfrom),
make_pair("sendmany", &sendmany),
make_pair("gettransaction", &gettransaction),
make_pair("listtransactions", &listtransactions),
make_pair("getwork", &getwork),
make_pair("listaccounts", &listaccounts),
make_pair("settxfee", &settxfee),
};
map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0]));
string pAllowInSafeMode[] =
{
"help",
"stop",
"getblockcount",
"getblocknumber",
"getconnectioncount",
"getdifficulty",
"getgenerate",
"setgenerate",
"gethashespersec",
"getinfo",
"getnewaddress",
"getaccountaddress",
"setlabel",
"getaccount",
"getlabel", // deprecated
"getaddressesbyaccount",
"getaddressesbylabel", // deprecated
"backupwallet",
"validateaddress",
"getwork",
};
set<string> setAllowInSafeMode(pAllowInSafeMode, pAllowInSafeMode + sizeof(pAllowInSafeMode)/sizeof(pAllowInSafeMode[0]));
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: bitcoin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want posix (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg)
{
if (nStatus == 401)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: bitcoin-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
string strStatus;
if (nStatus == 200) strStatus = "OK";
else if (nStatus == 400) strStatus = "Bad Request";
else if (nStatus == 403) strStatus = "Forbidden";
else if (nStatus == 404) strStatus = "Not Found";
else if (nStatus == 500) strStatus = "Internal Server Error";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: close\r\n"
"Content-Length: %d\r\n"
"Content-Type: application/json\r\n"
"Server: bitcoin-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
strStatus.c_str(),
rfc1123Time().c_str(),
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
int ReadHTTPStatus(std::basic_istream<char>& stream)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return 500;
return atoi(vWords[1].c_str());
}
int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
loop
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read status
int nStatus = ReadHTTPStatus(stream);
// Read header
int nLen = ReadHTTPHeader(stream, mapHeadersRet);
if (nLen < 0 || nLen > MAX_SIZE)
return 500;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
return nStatus;
}
string EncodeBase64(string s)
{
BIO *b64, *bmem;
BUF_MEM *bptr;
b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
bmem = BIO_new(BIO_s_mem());
b64 = BIO_push(b64, bmem);
BIO_write(b64, s.c_str(), s.size());
BIO_flush(b64);
BIO_get_mem_ptr(b64, &bptr);
string result(bptr->data, bptr->length);
BIO_free_all(b64);
return result;
}
string DecodeBase64(string s)
{
BIO *b64, *bmem;
char* buffer = static_cast<char*>(calloc(s.size(), sizeof(char)));
b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
bmem = BIO_new_mem_buf(const_cast<char*>(s.c_str()), s.size());
bmem = BIO_push(b64, bmem);
BIO_read(bmem, buffer, s.size());
BIO_free_all(bmem);
string result(buffer);
free(buffer);
return result;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
string::size_type nColon = strUserPass.find(":");
if (nColon == string::npos)
return false;
string strUser = strUserPass.substr(0, nColon);
string strPassword = strUserPass.substr(nColon+1);
return (strUser == mapArgs["-rpcuser"] && strPassword == mapArgs["-rpcpassword"]);
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = 500;
int code = find_value(objError, "code").get_int();
if (code == -32600) nStatus = 400;
else if (code == -32601) nStatus = 404;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply) << std::flush;
}
bool ClientAllowed(const string& strAddress)
{
if (strAddress == asio::ip::address_v4::loopback().to_string())
return true;
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
#ifdef USE_SSL
//
// IOStream device that speaks SSL but can also speak non-SSL
//
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(SSLStream &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
SSLStream& stream;
};
#endif
void ThreadRPCServer(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadRPCServer(parg));
try
{
vnThreadsRunning[4]++;
ThreadRPCServer2(parg);
vnThreadsRunning[4]--;
}
catch (std::exception& e) {
vnThreadsRunning[4]--;
PrintException(&e, "ThreadRPCServer()");
} catch (...) {
vnThreadsRunning[4]--;
PrintException(NULL, "ThreadRPCServer()");
}
printf("ThreadRPCServer exiting\n");
}
void ThreadRPCServer2(void* parg)
{
printf("ThreadRPCServer started\n");
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
{
string strWhatAmI = "To use bitcoind";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
PrintConsole(
_("Warning: %s, you must set rpcpassword=<password>\nin the configuration file: %s\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"),
strWhatAmI.c_str(),
GetConfigFile().c_str());
CreateThread(Shutdown, NULL);
return;
}
bool fUseSSL = GetBoolArg("-rpcssl");
asio::ip::address bindAddress = mapArgs.count("-rpcallowip") ? asio::ip::address_v4::any() : asio::ip::address_v4::loopback();
asio::io_service io_service;
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", 8332));
ip::tcp::acceptor acceptor(io_service, endpoint);
acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
#ifdef USE_SSL
ssl::context context(io_service, ssl::context::sslv23);
if (fUseSSL)
{
context.set_options(ssl::context::no_sslv2);
filesystem::path certfile = GetArg("-rpcsslcertificatechainfile", "server.cert");
if (!certfile.is_complete()) certfile = filesystem::path(GetDataDir()) / certfile;
if (filesystem::exists(certfile)) context.use_certificate_chain_file(certfile.string().c_str());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", certfile.string().c_str());
filesystem::path pkfile = GetArg("-rpcsslprivatekeyfile", "server.pem");
if (!pkfile.is_complete()) pkfile = filesystem::path(GetDataDir()) / pkfile;
if (filesystem::exists(pkfile)) context.use_private_key_file(pkfile.string().c_str(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pkfile.string().c_str());
string ciphers = GetArg("-rpcsslciphers",
"TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(context.impl(), ciphers.c_str());
}
#else
if (fUseSSL)
throw runtime_error("-rpcssl=1, but bitcoin compiled without full openssl libraries.");
#endif
loop
{
// Accept connection
#ifdef USE_SSL
SSLStream sslStream(io_service, context);
SSLIOStreamDevice d(sslStream, fUseSSL);
iostreams::stream<SSLIOStreamDevice> stream(d);
#else
ip::tcp::iostream stream;
#endif
ip::tcp::endpoint peer;
vnThreadsRunning[4]--;
#ifdef USE_SSL
acceptor.accept(sslStream.lowest_layer(), peer);
#else
acceptor.accept(*stream.rdbuf(), peer);
#endif
vnThreadsRunning[4]++;
if (fShutdown)
return;
// Restrict callers by IP
if (!ClientAllowed(peer.address().to_string()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
stream << HTTPReply(403, "") << std::flush;
continue;
}
map<string, string> mapHeaders;
string strRequest;
boost::thread api_caller(ReadHTTP, boost::ref(stream), boost::ref(mapHeaders), boost::ref(strRequest));
if (!api_caller.timed_join(boost::posix_time::seconds(GetArg("-rpctimeout", 30))))
{ // Timed out:
acceptor.cancel();
printf("ThreadRPCServer ReadHTTP timeout\n");
continue;
}
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
stream << HTTPReply(401, "") << std::flush;
continue;
}
if (!HTTPAuthorized(mapHeaders))
{
// Deter brute-forcing short passwords
if (mapArgs["-rpcpassword"].size() < 15)
Sleep(50);
stream << HTTPReply(401, "") << std::flush;
printf("ThreadRPCServer incorrect password attempt\n");
continue;
}
Value id = Value::null;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest) || valRequest.type() != obj_type)
throw JSONRPCError(-32700, "Parse error");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(-32600, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(-32600, "Method must be a string");
string strMethod = valMethod.get_str();
if (strMethod != "getwork")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
Array params;
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(-32600, "Params must be an array");
// Find method
map<string, rpcfn_type>::iterator mi = mapCallTable.find(strMethod);
if (mi == mapCallTable.end())
throw JSONRPCError(-32601, "Method not found");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") && !setAllowInSafeMode.count(strMethod))
throw JSONRPCError(-2, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result = (*(*mi).second)(params, false);
// Send reply
string strReply = JSONRPCReply(result, Value::null, id);
stream << HTTPReply(200, strReply) << std::flush;
}
catch (std::exception& e)
{
ErrorReply(stream, JSONRPCError(-1, e.what()), id);
}
}
catch (Object& objError)
{
ErrorReply(stream, objError, id);
}
catch (std::exception& e)
{
ErrorReply(stream, JSONRPCError(-32700, e.what()), id);
}
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
#ifdef USE_SSL
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
SSLStream sslStream(io_service, context);
SSLIOStreamDevice d(sslStream, fUseSSL);
iostreams::stream<SSLIOStreamDevice> stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332")))
throw runtime_error("couldn't connect to server");
#else
if (fUseSSL)
throw runtime_error("-rpcssl=1, but bitcoin compiled without full openssl libraries.");
ip::tcp::iostream stream(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", "8332"));
if (stream.fail())
throw runtime_error("couldn't connect to server");
#endif
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive reply
map<string, string> mapHeaders;
string strReply;
int nStatus = ReadHTTP(stream, mapHeaders, strReply);
if (nStatus == 401)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != 400 && nStatus != 404 && nStatus != 500)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value)
{
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
if (!read_string(value.get_str(), value2))
throw runtime_error("type mismatch");
value = value2.get_value<T>();
}
else
{
value = value.get_value<T>();
}
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
Array params;
for (int i = 2; i < argc; i++)
params.push_back(argv[i]);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getamountreceived" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbylabel" && n > 1) ConvertTo<boost::int64_t>(params[1]); // deprecated
if (strMethod == "getallreceived" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
if (strMethod == "getallreceived" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbylabel" && n > 0) ConvertTo<boost::int64_t>(params[0]); // deprecated
if (strMethod == "listreceivedbylabel" && n > 1) ConvertTo<bool>(params[1]); // deprecated
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "sendmany" && n > 1)
{
string s = params[1].get_str();
Value v;
if (!read_string(s, v) || v.type() != obj_type)
throw runtime_error("type mismatch");
params[1] = v.get_obj();
}
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
const Value& id = find_value(reply, "id");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (std::exception& e)
{
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...)
{
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
#if defined(__WXMSW__) && defined(GUI)
// Windows GUI apps can't print to command line,
// so settle for a message box yuck
MyMessageBox(strPrint, "Bitcoin", wxOK);
#else
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
#endif
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
diff --git a/src/ui.cpp b/src/ui.cpp
index a49741f54..2cbcfd5bd 100644
--- a/src/ui.cpp
+++ b/src/ui.cpp
@@ -1,2957 +1,2964 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "headers.h"
#include "db.h"
#include "init.h"
#include "strlcpy.h"
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>
#ifdef _MSC_VER
#include <crtdbg.h>
#endif
using namespace std;
using namespace boost;
DEFINE_EVENT_TYPE(wxEVT_UITHREADCALL)
CMainFrame* pframeMain = NULL;
CMyTaskBarIcon* ptaskbaricon = NULL;
bool fClosedToTray = false;
wxLocale g_locale;
#ifdef __WXMSW__
double nScaleX = 1.0;
double nScaleY = 1.0;
#else
static const double nScaleX = 1.0;
static const double nScaleY = 1.0;
#endif
//////////////////////////////////////////////////////////////////////////////
//
// Util
//
void HandleCtrlA(wxKeyEvent& event)
{
// Ctrl-a select all
event.Skip();
wxTextCtrl* textCtrl = (wxTextCtrl*)event.GetEventObject();
if (event.GetModifiers() == wxMOD_CONTROL && event.GetKeyCode() == 'A')
textCtrl->SetSelection(-1, -1);
}
bool Is24HourTime()
{
//char pszHourFormat[256];
//pszHourFormat[0] = '\0';
//GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_ITIME, pszHourFormat, 256);
//return (pszHourFormat[0] != '0');
return true;
}
string DateStr(int64 nTime)
{
// Can only be used safely here in the UI
return (string)wxDateTime((time_t)nTime).FormatDate();
}
string DateTimeStr(int64 nTime)
{
// Can only be used safely here in the UI
wxDateTime datetime((time_t)nTime);
if (Is24HourTime())
return (string)datetime.Format("%x %H:%M");
else
return (string)datetime.Format("%x ") + itostr((datetime.GetHour() + 11) % 12 + 1) + (string)datetime.Format(":%M %p");
}
wxString GetItemText(wxListCtrl* listCtrl, int nIndex, int nColumn)
{
// Helper to simplify access to listctrl
wxListItem item;
item.m_itemId = nIndex;
item.m_col = nColumn;
item.m_mask = wxLIST_MASK_TEXT;
if (!listCtrl->GetItem(item))
return "";
return item.GetText();
}
int InsertLine(wxListCtrl* listCtrl, const wxString& str0, const wxString& str1)
{
int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);
listCtrl->SetItem(nIndex, 1, str1);
return nIndex;
}
int InsertLine(wxListCtrl* listCtrl, const wxString& str0, const wxString& str1, const wxString& str2, const wxString& str3, const wxString& str4)
{
int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);
listCtrl->SetItem(nIndex, 1, str1);
listCtrl->SetItem(nIndex, 2, str2);
listCtrl->SetItem(nIndex, 3, str3);
listCtrl->SetItem(nIndex, 4, str4);
return nIndex;
}
int InsertLine(wxListCtrl* listCtrl, void* pdata, const wxString& str0, const wxString& str1, const wxString& str2, const wxString& str3, const wxString& str4)
{
int nIndex = listCtrl->InsertItem(listCtrl->GetItemCount(), str0);
listCtrl->SetItemPtrData(nIndex, (wxUIntPtr)pdata);
listCtrl->SetItem(nIndex, 1, str1);
listCtrl->SetItem(nIndex, 2, str2);
listCtrl->SetItem(nIndex, 3, str3);
listCtrl->SetItem(nIndex, 4, str4);
return nIndex;
}
void SetItemTextColour(wxListCtrl* listCtrl, int nIndex, const wxColour& colour)
{
// Repaint on Windows is more flickery if the colour has ever been set,
// so don't want to set it unless it's different. Default colour has
// alpha 0 transparent, so our colours don't match using operator==.
wxColour c1 = listCtrl->GetItemTextColour(nIndex);
if (!c1.IsOk())
c1 = wxColour(0,0,0);
if (colour.Red() != c1.Red() || colour.Green() != c1.Green() || colour.Blue() != c1.Blue())
listCtrl->SetItemTextColour(nIndex, colour);
}
void SetSelection(wxListCtrl* listCtrl, int nIndex)
{
int nSize = listCtrl->GetItemCount();
long nState = (wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);
for (int i = 0; i < nSize; i++)
listCtrl->SetItemState(i, (i == nIndex ? nState : 0), nState);
}
int GetSelection(wxListCtrl* listCtrl)
{
int nSize = listCtrl->GetItemCount();
for (int i = 0; i < nSize; i++)
if (listCtrl->GetItemState(i, wxLIST_STATE_FOCUSED))
return i;
return -1;
}
string HtmlEscape(const char* psz, bool fMultiLine=false)
{
int len = 0;
for (const char* p = psz; *p; p++)
{
if (*p == '<') len += 4;
else if (*p == '>') len += 4;
else if (*p == '&') len += 5;
else if (*p == '"') len += 6;
else if (*p == ' ' && p > psz && p[-1] == ' ' && p[1] == ' ') len += 6;
else if (*p == '\n' && fMultiLine) len += 5;
else
len++;
}
string str;
str.reserve(len);
for (const char* p = psz; *p; p++)
{
if (*p == '<') str += "&lt;";
else if (*p == '>') str += "&gt;";
else if (*p == '&') str += "&amp;";
else if (*p == '"') str += "&quot;";
else if (*p == ' ' && p > psz && p[-1] == ' ' && p[1] == ' ') str += "&nbsp;";
else if (*p == '\n' && fMultiLine) str += "<br>\n";
else
str += *p;
}
return str;
}
string HtmlEscape(const string& str, bool fMultiLine=false)
{
return HtmlEscape(str.c_str(), fMultiLine);
}
void CalledMessageBox(const string& message, const string& caption, int style, wxWindow* parent, int x, int y, int* pnRet, bool* pfDone)
{
*pnRet = wxMessageBox(message, caption, style, parent, x, y);
*pfDone = true;
}
int ThreadSafeMessageBox(const string& message, const string& caption, int style, wxWindow* parent, int x, int y)
{
#ifdef __WXMSW__
return wxMessageBox(message, caption, style, parent, x, y);
#else
if (wxThread::IsMain() || fDaemon)
{
return wxMessageBox(message, caption, style, parent, x, y);
}
else
{
int nRet = 0;
bool fDone = false;
UIThreadCall(bind(CalledMessageBox, message, caption, style, parent, x, y, &nRet, &fDone));
while (!fDone)
Sleep(100);
return nRet;
}
#endif
}
bool ThreadSafeAskFee(int64 nFeeRequired, const string& strCaption, wxWindow* parent)
{
if (nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
string strMessage = strprintf(
_("This transaction is over the size limit. You can still send it for a fee of %s, "
"which goes to the nodes that process your transaction and helps to support the network. "
"Do you want to pay the fee?"),
FormatMoney(nFeeRequired).c_str());
return (ThreadSafeMessageBox(strMessage, strCaption, wxYES_NO, parent) == wxYES);
}
void CalledSetStatusBar(const string& strText, int nField)
{
if (nField == 0 && GetWarnings("statusbar") != "")
return;
if (pframeMain && pframeMain->m_statusBar)
pframeMain->m_statusBar->SetStatusText(strText, nField);
}
void SetDefaultReceivingAddress(const string& strAddress)
{
// Update main window address and database
if (pframeMain == NULL)
return;
if (strAddress != pframeMain->m_textCtrlAddress->GetValue())
{
uint160 hash160;
if (!AddressToHash160(strAddress, hash160))
return;
if (!mapPubKeys.count(hash160))
return;
CWalletDB(pwalletMain->strWalletFile).WriteDefaultKey(mapPubKeys[hash160]);
pframeMain->m_textCtrlAddress->SetValue(strAddress);
}
}
//////////////////////////////////////////////////////////////////////////////
//
// CMainFrame
//
CMainFrame::CMainFrame(wxWindow* parent) : CMainFrameBase(parent)
{
Connect(wxEVT_UITHREADCALL, wxCommandEventHandler(CMainFrame::OnUIThreadCall), NULL, this);
// Set initially selected page
wxNotebookEvent event;
event.SetSelection(0);
OnNotebookPageChanged(event);
m_notebook->ChangeSelection(0);
// Init
fRefreshListCtrl = false;
fRefreshListCtrlRunning = false;
fOnSetFocusAddress = false;
fRefresh = false;
m_choiceFilter->SetSelection(0);
double dResize = nScaleX;
#ifdef __WXMSW__
SetIcon(wxICON(bitcoin));
SetSize(dResize * GetSize().GetWidth(), nScaleY * GetSize().GetHeight());
#else
SetIcon(bitcoin80_xpm);
SetBackgroundColour(m_toolBar->GetBackgroundColour());
wxFont fontTmp = m_staticText41->GetFont();
fontTmp.SetFamily(wxFONTFAMILY_TELETYPE);
m_staticTextBalance->SetFont(fontTmp);
m_staticTextBalance->SetSize(140, 17);
// resize to fit ubuntu's huge default font
dResize = 1.22;
SetSize(dResize * GetSize().GetWidth(), 1.15 * GetSize().GetHeight());
#endif
m_staticTextBalance->SetLabel(FormatMoney(pwalletMain->GetBalance()) + " ");
m_listCtrl->SetFocus();
ptaskbaricon = new CMyTaskBarIcon();
#ifdef __WXMAC_OSX__
// Mac automatically moves wxID_EXIT, wxID_PREFERENCES and wxID_ABOUT
// to their standard places, leaving these menus empty.
GetMenuBar()->Remove(2); // remove Help menu
GetMenuBar()->Remove(0); // remove File menu
#endif
// Init column headers
int nDateWidth = DateTimeStr(1229413914).size() * 6 + 8;
if (!strstr(DateTimeStr(1229413914).c_str(), "2008"))
nDateWidth += 12;
#ifdef __WXMAC_OSX__
nDateWidth += 5;
dResize -= 0.01;
#endif
wxListCtrl* pplistCtrl[] = {m_listCtrlAll, m_listCtrlSentReceived, m_listCtrlSent, m_listCtrlReceived};
BOOST_FOREACH(wxListCtrl* p, pplistCtrl)
{
p->InsertColumn(0, "", wxLIST_FORMAT_LEFT, dResize * 0);
p->InsertColumn(1, "", wxLIST_FORMAT_LEFT, dResize * 0);
p->InsertColumn(2, _("Status"), wxLIST_FORMAT_LEFT, dResize * 112);
p->InsertColumn(3, _("Date"), wxLIST_FORMAT_LEFT, dResize * nDateWidth);
p->InsertColumn(4, _("Description"), wxLIST_FORMAT_LEFT, dResize * 409 - nDateWidth);
p->InsertColumn(5, _("Debit"), wxLIST_FORMAT_RIGHT, dResize * 79);
p->InsertColumn(6, _("Credit"), wxLIST_FORMAT_RIGHT, dResize * 79);
}
// Init status bar
int pnWidths[3] = { -100, 88, 300 };
#ifndef __WXMSW__
pnWidths[1] = pnWidths[1] * 1.1 * dResize;
pnWidths[2] = pnWidths[2] * 1.1 * dResize;
#endif
m_statusBar->SetFieldsCount(3, pnWidths);
// Fill your address text box
vector<unsigned char> vchPubKey;
if (CWalletDB(pwalletMain->strWalletFile,"r").ReadDefaultKey(vchPubKey))
m_textCtrlAddress->SetValue(PubKeyToAddress(vchPubKey));
// Fill listctrl with wallet transactions
RefreshListCtrl();
}
CMainFrame::~CMainFrame()
{
pframeMain = NULL;
delete ptaskbaricon;
ptaskbaricon = NULL;
}
void CMainFrame::OnNotebookPageChanged(wxNotebookEvent& event)
{
event.Skip();
nPage = event.GetSelection();
if (nPage == ALL)
{
m_listCtrl = m_listCtrlAll;
fShowGenerated = true;
fShowSent = true;
fShowReceived = true;
}
else if (nPage == SENTRECEIVED)
{
m_listCtrl = m_listCtrlSentReceived;
fShowGenerated = false;
fShowSent = true;
fShowReceived = true;
}
else if (nPage == SENT)
{
m_listCtrl = m_listCtrlSent;
fShowGenerated = false;
fShowSent = true;
fShowReceived = false;
}
else if (nPage == RECEIVED)
{
m_listCtrl = m_listCtrlReceived;
fShowGenerated = false;
fShowSent = false;
fShowReceived = true;
}
RefreshListCtrl();
m_listCtrl->SetFocus();
}
void CMainFrame::OnClose(wxCloseEvent& event)
{
if (fMinimizeOnClose && event.CanVeto() && !IsIconized())
{
// Divert close to minimize
event.Veto();
fClosedToTray = true;
Iconize(true);
}
else
{
Destroy();
CreateThread(Shutdown, NULL);
}
}
void CMainFrame::OnIconize(wxIconizeEvent& event)
{
event.Skip();
// Hide the task bar button when minimized.
// Event is sent when the frame is minimized or restored.
// wxWidgets 2.8.9 doesn't have IsIconized() so there's no way
// to get rid of the deprecated warning. Just ignore it.
if (!event.Iconized())
fClosedToTray = false;
#if defined(__WXGTK__) || defined(__WXMAC_OSX__)
if (GetBoolArg("-minimizetotray")) {
#endif
// The tray icon sometimes disappears on ubuntu karmic
// Hiding the taskbar button doesn't work cleanly on ubuntu lucid
// Reports of CPU peg on 64-bit linux
if (fMinimizeToTray && event.Iconized())
fClosedToTray = true;
Show(!fClosedToTray);
ptaskbaricon->Show(fMinimizeToTray || fClosedToTray);
#if defined(__WXGTK__) || defined(__WXMAC_OSX__)
}
#endif
}
void CMainFrame::OnMouseEvents(wxMouseEvent& event)
{
event.Skip();
RandAddSeed();
RAND_add(&event.m_x, sizeof(event.m_x), 0.25);
RAND_add(&event.m_y, sizeof(event.m_y), 0.25);
}
void CMainFrame::OnListColBeginDrag(wxListEvent& event)
{
// Hidden columns not resizeable
if (event.GetColumn() <= 1 && !fDebug)
event.Veto();
else
event.Skip();
}
int CMainFrame::GetSortIndex(const string& strSort)
{
#ifdef __WXMSW__
return 0;
#else
// The wx generic listctrl implementation used on GTK doesn't sort,
// so we have to do it ourselves. Remember, we sort in reverse order.
// In the wx generic implementation, they store the list of items
// in a vector, so indexed lookups are fast, but inserts are slower
// the closer they are to the top.
int low = 0;
int high = m_listCtrl->GetItemCount();
while (low < high)
{
int mid = low + ((high - low) / 2);
if (strSort.compare(m_listCtrl->GetItemText(mid).c_str()) >= 0)
high = mid;
else
low = mid + 1;
}
return low;
#endif
}
void CMainFrame::InsertLine(bool fNew, int nIndex, uint256 hashKey, string strSort, const wxColour& colour, const wxString& str2, const wxString& str3, const wxString& str4, const wxString& str5, const wxString& str6)
{
strSort = " " + strSort; // leading space to workaround wx2.9.0 ubuntu 9.10 bug
long nData = *(long*)&hashKey; // where first char of hidden column is displayed
// Find item
if (!fNew && nIndex == -1)
{
string strHash = " " + hashKey.ToString();
while ((nIndex = m_listCtrl->FindItem(nIndex, nData)) != -1)
if (GetItemText(m_listCtrl, nIndex, 1) == strHash)
break;
}
// fNew is for blind insert, only use if you're sure it's new
if (fNew || nIndex == -1)
{
nIndex = m_listCtrl->InsertItem(GetSortIndex(strSort), strSort);
}
else
{
// If sort key changed, must delete and reinsert to make it relocate
if (GetItemText(m_listCtrl, nIndex, 0) != strSort)
{
m_listCtrl->DeleteItem(nIndex);
nIndex = m_listCtrl->InsertItem(GetSortIndex(strSort), strSort);
}
}
m_listCtrl->SetItem(nIndex, 1, " " + hashKey.ToString());
m_listCtrl->SetItem(nIndex, 2, str2);
m_listCtrl->SetItem(nIndex, 3, str3);
m_listCtrl->SetItem(nIndex, 4, str4);
m_listCtrl->SetItem(nIndex, 5, str5);
m_listCtrl->SetItem(nIndex, 6, str6);
m_listCtrl->SetItemData(nIndex, nData);
SetItemTextColour(m_listCtrl, nIndex, colour);
}
bool CMainFrame::DeleteLine(uint256 hashKey)
{
long nData = *(long*)&hashKey;
// Find item
int nIndex = -1;
string strHash = " " + hashKey.ToString();
while ((nIndex = m_listCtrl->FindItem(nIndex, nData)) != -1)
if (GetItemText(m_listCtrl, nIndex, 1) == strHash)
break;
if (nIndex != -1)
m_listCtrl->DeleteItem(nIndex);
return nIndex != -1;
}
string FormatTxStatus(const CWalletTx& wtx)
{
// Status
if (!wtx.IsFinal())
{
if (wtx.nLockTime < 500000000)
return strprintf(_("Open for %d blocks"), nBestHeight - wtx.nLockTime);
else
return strprintf(_("Open until %s"), DateTimeStr(wtx.nLockTime).c_str());
}
else
{
int nDepth = wtx.GetDepthInMainChain();
if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
return strprintf(_("%d/offline?"), nDepth);
else if (nDepth < 6)
return strprintf(_("%d/unconfirmed"), nDepth);
else
return strprintf(_("%d confirmations"), nDepth);
}
}
string SingleLine(const string& strIn)
{
string strOut;
bool fOneSpace = false;
BOOST_FOREACH(unsigned char c, strIn)
{
if (isspace(c))
{
fOneSpace = true;
}
else if (c > ' ')
{
if (fOneSpace && !strOut.empty())
strOut += ' ';
strOut += c;
fOneSpace = false;
}
}
return strOut;
}
bool CMainFrame::InsertTransaction(const CWalletTx& wtx, bool fNew, int nIndex)
{
int64 nTime = wtx.nTimeDisplayed = wtx.GetTxTime();
int64 nCredit = wtx.GetCredit(true);
int64 nDebit = wtx.GetDebit();
int64 nNet = nCredit - nDebit;
uint256 hash = wtx.GetHash();
string strStatus = FormatTxStatus(wtx);
bool fConfirmed = wtx.fConfirmedDisplayed = wtx.IsConfirmed();
wxColour colour = (fConfirmed ? wxColour(0,0,0) : wxColour(128,128,128));
map<string, string> mapValue = wtx.mapValue;
wtx.nLinesDisplayed = 1;
nListViewUpdated++;
// Filter
if (wtx.IsCoinBase())
{
// Don't show generated coin until confirmed by at least one block after it
// so we don't get the user's hopes up until it looks like it's probably accepted.
//
// It is not an error when generated blocks are not accepted. By design,
// some percentage of blocks, like 10% or more, will end up not accepted.
// This is the normal mechanism by which the network copes with latency.
//
// We display regular transactions right away before any confirmation
// because they can always get into some block eventually. Generated coins
// are special because if their block is not accepted, they are not valid.
//
if (wtx.GetDepthInMainChain() < 2)
{
wtx.nLinesDisplayed = 0;
return false;
}
if (!fShowGenerated)
return false;
}
// Find the block the tx is in
CBlockIndex* pindex = NULL;
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock);
if (mi != mapBlockIndex.end())
pindex = (*mi).second;
// Sort order, unrecorded transactions sort to the top
string strSort = strprintf("%010d-%01d-%010u",
(pindex ? pindex->nHeight : INT_MAX),
(wtx.IsCoinBase() ? 1 : 0),
wtx.nTimeReceived);
// Insert line
if (nNet > 0 || wtx.IsCoinBase())
{
//
// Credit
//
string strDescription;
if (wtx.IsCoinBase())
{
// Generated
strDescription = _("Generated");
if (nCredit == 0)
{
int64 nUnmatured = 0;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
nUnmatured += pwalletMain->GetCredit(txout);
if (wtx.IsInMainChain())
{
strDescription = strprintf(_("Generated (%s matures in %d more blocks)"), FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());
// Check if the block was requested by anyone
if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
strDescription = _("Generated - Warning: This block was not received by any other nodes and will probably not be accepted!");
}
else
{
strDescription = _("Generated (not accepted)");
}
}
}
else if (!mapValue["from"].empty() || !mapValue["message"].empty())
{
// Received by IP connection
if (!fShowReceived)
return false;
if (!mapValue["from"].empty())
strDescription += _("From: ") + mapValue["from"];
if (!mapValue["message"].empty())
{
if (!strDescription.empty())
strDescription += " - ";
strDescription += mapValue["message"];
}
}
else
{
// Received by Bitcoin Address
if (!fShowReceived)
return false;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
if (pwalletMain->IsMine(txout))
{
vector<unsigned char> vchPubKey;
if (ExtractPubKey(txout.scriptPubKey, pwalletMain, vchPubKey))
{
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
//strDescription += _("Received payment to ");
//strDescription += _("Received with address ");
strDescription += _("Received with: ");
string strAddress = PubKeyToAddress(vchPubKey);
map<string, string>::iterator mi = pwalletMain->mapAddressBook.find(strAddress);
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
{
string strLabel = (*mi).second;
strDescription += strAddress.substr(0,12) + "... ";
strDescription += "(" + strLabel + ")";
}
else
strDescription += strAddress;
}
}
break;
}
}
}
string strCredit = FormatMoney(nNet, true);
if (!fConfirmed)
strCredit = "[" + strCredit + "]";
InsertLine(fNew, nIndex, hash, strSort, colour,
strStatus,
nTime ? DateTimeStr(nTime) : "",
SingleLine(strDescription),
"",
strCredit);
}
else
{
bool fAllFromMe = true;
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
fAllFromMe = fAllFromMe && pwalletMain->IsMine(txin);
bool fAllToMe = true;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
fAllToMe = fAllToMe && pwalletMain->IsMine(txout);
if (fAllFromMe && fAllToMe)
{
// Payment to self
int64 nChange = wtx.GetChange();
InsertLine(fNew, nIndex, hash, strSort, colour,
strStatus,
nTime ? DateTimeStr(nTime) : "",
_("Payment to yourself"),
FormatMoney(-(nDebit - nChange), true),
FormatMoney(nCredit - nChange, true));
}
else if (fAllFromMe)
{
//
// Debit
//
if (!fShowSent)
return false;
int64 nTxFee = nDebit - wtx.GetValueOut();
wtx.nLinesDisplayed = 0;
for (int nOut = 0; nOut < wtx.vout.size(); nOut++)
{
const CTxOut& txout = wtx.vout[nOut];
if (pwalletMain->IsMine(txout))
continue;
string strAddress;
if (!mapValue["to"].empty())
{
// Sent to IP
strAddress = mapValue["to"];
}
else
{
// Sent to Bitcoin Address
uint160 hash160;
if (ExtractHash160(txout.scriptPubKey, hash160))
strAddress = Hash160ToAddress(hash160);
}
string strDescription = _("To: ");
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
if (pwalletMain->mapAddressBook.count(strAddress) && !pwalletMain->mapAddressBook[strAddress].empty())
strDescription += pwalletMain->mapAddressBook[strAddress] + " ";
strDescription += strAddress;
if (!mapValue["message"].empty())
{
if (!strDescription.empty())
strDescription += " - ";
strDescription += mapValue["message"];
}
else if (!mapValue["comment"].empty())
{
if (!strDescription.empty())
strDescription += " - ";
strDescription += mapValue["comment"];
}
int64 nValue = txout.nValue;
if (nTxFee > 0)
{
nValue += nTxFee;
nTxFee = 0;
}
InsertLine(fNew, nIndex, hash, strprintf("%s-%d", strSort.c_str(), nOut), colour,
strStatus,
nTime ? DateTimeStr(nTime) : "",
SingleLine(strDescription),
FormatMoney(-nValue, true),
"");
nIndex = -1;
wtx.nLinesDisplayed++;
}
}
else
{
//
// Mixed debit transaction, can't break down payees
//
bool fAllMine = true;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
fAllMine = fAllMine && pwalletMain->IsMine(txout);
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
fAllMine = fAllMine && pwalletMain->IsMine(txin);
InsertLine(fNew, nIndex, hash, strSort, colour,
strStatus,
nTime ? DateTimeStr(nTime) : "",
"",
FormatMoney(nNet, true),
"");
}
}
return true;
}
void CMainFrame::RefreshListCtrl()
{
fRefreshListCtrl = true;
::wxWakeUpIdle();
}
void CMainFrame::OnIdle(wxIdleEvent& event)
{
if (fRefreshListCtrl)
{
// Collect list of wallet transactions and sort newest first
bool fEntered = false;
vector<pair<unsigned int, uint256> > vSorted;
TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
printf("RefreshListCtrl starting\n");
fEntered = true;
fRefreshListCtrl = false;
pwalletMain->vWalletUpdated.clear();
// Do the newest transactions first
vSorted.reserve(pwalletMain->mapWallet.size());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
unsigned int nTime = UINT_MAX - wtx.GetTxTime();
vSorted.push_back(make_pair(nTime, (*it).first));
}
m_listCtrl->DeleteAllItems();
}
if (!fEntered)
return;
sort(vSorted.begin(), vSorted.end());
// Fill list control
for (int i = 0; i < vSorted.size();)
{
if (fShutdown)
return;
bool fEntered = false;
TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
fEntered = true;
uint256& hash = vSorted[i++].second;
map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
if (mi != pwalletMain->mapWallet.end())
InsertTransaction((*mi).second, true);
}
if (!fEntered || i == 100 || i % 500 == 0)
wxYield();
}
printf("RefreshListCtrl done\n");
// Update transaction total display
MainFrameRepaint();
}
else
{
// Check for time updates
static int64 nLastTime;
if (GetTime() > nLastTime + 30)
{
TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
nLastTime = GetTime();
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
CWalletTx& wtx = (*it).second;
if (wtx.nTimeDisplayed && wtx.nTimeDisplayed != wtx.GetTxTime())
InsertTransaction(wtx, false);
}
}
}
}
}
void CMainFrame::RefreshStatusColumn()
{
static int nLastTop;
static CBlockIndex* pindexLastBest;
static unsigned int nLastRefreshed;
int nTop = max((int)m_listCtrl->GetTopItem(), 0);
if (nTop == nLastTop && pindexLastBest == pindexBest)
return;
TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
int nStart = nTop;
int nEnd = min(nStart + 100, m_listCtrl->GetItemCount());
if (pindexLastBest == pindexBest && nLastRefreshed == nListViewUpdated)
{
// If no updates, only need to do the part that moved onto the screen
if (nStart >= nLastTop && nStart < nLastTop + 100)
nStart = nLastTop + 100;
if (nEnd >= nLastTop && nEnd < nLastTop + 100)
nEnd = nLastTop;
}
nLastTop = nTop;
pindexLastBest = pindexBest;
nLastRefreshed = nListViewUpdated;
for (int nIndex = nStart; nIndex < min(nEnd, m_listCtrl->GetItemCount()); nIndex++)
{
uint256 hash((string)GetItemText(m_listCtrl, nIndex, 1));
map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
if (mi == pwalletMain->mapWallet.end())
{
printf("CMainFrame::RefreshStatusColumn() : tx not found in mapWallet\n");
continue;
}
CWalletTx& wtx = (*mi).second;
if (wtx.IsCoinBase() ||
wtx.GetTxTime() != wtx.nTimeDisplayed ||
wtx.IsConfirmed() != wtx.fConfirmedDisplayed)
{
if (!InsertTransaction(wtx, false, nIndex))
m_listCtrl->DeleteItem(nIndex--);
}
else
{
m_listCtrl->SetItem(nIndex, 2, FormatTxStatus(wtx));
}
}
}
}
void CMainFrame::OnPaint(wxPaintEvent& event)
{
event.Skip();
if (fRefresh)
{
fRefresh = false;
Refresh();
}
}
unsigned int nNeedRepaint = 0;
unsigned int nLastRepaint = 0;
int64 nLastRepaintTime = 0;
int64 nRepaintInterval = 500;
void ThreadDelayedRepaint(void* parg)
{
while (!fShutdown)
{
if (nLastRepaint != nNeedRepaint && GetTimeMillis() - nLastRepaintTime >= nRepaintInterval)
{
nLastRepaint = nNeedRepaint;
if (pframeMain)
{
printf("DelayedRepaint\n");
wxPaintEvent event;
pframeMain->fRefresh = true;
pframeMain->GetEventHandler()->AddPendingEvent(event);
}
}
Sleep(nRepaintInterval);
}
}
void MainFrameRepaint()
{
// This is called by network code that shouldn't access pframeMain
// directly because it could still be running after the UI is closed.
if (pframeMain)
{
// Don't repaint too often
static int64 nLastRepaintRequest;
if (GetTimeMillis() - nLastRepaintRequest < 100)
{
nNeedRepaint++;
return;
}
nLastRepaintRequest = GetTimeMillis();
printf("MainFrameRepaint\n");
wxPaintEvent event;
pframeMain->fRefresh = true;
pframeMain->GetEventHandler()->AddPendingEvent(event);
}
}
void CMainFrame::OnPaintListCtrl(wxPaintEvent& event)
{
// Skip lets the listctrl do the paint, we're just hooking the message
event.Skip();
if (ptaskbaricon)
ptaskbaricon->UpdateTooltip();
//
// Slower stuff
//
static int nTransactionCount;
bool fPaintedBalance = false;
if (GetTimeMillis() - nLastRepaintTime >= nRepaintInterval)
{
nLastRepaint = nNeedRepaint;
nLastRepaintTime = GetTimeMillis();
// Update listctrl contents
if (!pwalletMain->vWalletUpdated.empty())
{
TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
string strTop;
if (m_listCtrl->GetItemCount())
strTop = (string)m_listCtrl->GetItemText(0);
BOOST_FOREACH(uint256 hash, pwalletMain->vWalletUpdated)
{
map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
if (mi != pwalletMain->mapWallet.end())
InsertTransaction((*mi).second, false);
}
pwalletMain->vWalletUpdated.clear();
if (m_listCtrl->GetItemCount() && strTop != (string)m_listCtrl->GetItemText(0))
m_listCtrl->ScrollList(0, INT_MIN/2);
}
}
// Balance total
TRY_CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
fPaintedBalance = true;
m_staticTextBalance->SetLabel(FormatMoney(pwalletMain->GetBalance()) + " ");
// Count hidden and multi-line transactions
nTransactionCount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
CWalletTx& wtx = (*it).second;
nTransactionCount += wtx.nLinesDisplayed;
}
}
}
if (!pwalletMain->vWalletUpdated.empty() || !fPaintedBalance)
nNeedRepaint++;
// Update status column of visible items only
RefreshStatusColumn();
// Update status bar
static string strPrevWarning;
string strWarning = GetWarnings("statusbar");
if (strWarning != "")
m_statusBar->SetStatusText(string(" ") + _(strWarning), 0);
else if (strPrevWarning != "")
m_statusBar->SetStatusText("", 0);
strPrevWarning = strWarning;
string strGen = "";
if (fGenerateBitcoins)
strGen = _(" Generating");
if (fGenerateBitcoins && vNodes.empty())
strGen = _("(not connected)");
m_statusBar->SetStatusText(strGen, 1);
string strStatus = strprintf(_(" %d connections %d blocks %d transactions"), vNodes.size(), nBestHeight, nTransactionCount);
m_statusBar->SetStatusText(strStatus, 2);
// Update receiving address
string strDefaultAddress = PubKeyToAddress(pwalletMain->vchDefaultKey);
if (m_textCtrlAddress->GetValue() != strDefaultAddress)
m_textCtrlAddress->SetValue(strDefaultAddress);
}
void UIThreadCall(boost::function0<void> fn)
{
// Call this with a function object created with bind.
// bind needs all parameters to match the function's expected types
// and all default parameters specified. Some examples:
// UIThreadCall(bind(wxBell));
// UIThreadCall(bind(wxMessageBox, wxT("Message"), wxT("Title"), wxOK, (wxWindow*)NULL, -1, -1));
// UIThreadCall(bind(&CMainFrame::OnMenuHelpAbout, pframeMain, event));
if (pframeMain)
{
wxCommandEvent event(wxEVT_UITHREADCALL);
event.SetClientData((void*)new boost::function0<void>(fn));
pframeMain->GetEventHandler()->AddPendingEvent(event);
}
}
void CMainFrame::OnUIThreadCall(wxCommandEvent& event)
{
boost::function0<void>* pfn = (boost::function0<void>*)event.GetClientData();
(*pfn)();
delete pfn;
}
void CMainFrame::OnMenuFileExit(wxCommandEvent& event)
{
// File->Exit
Close(true);
}
void CMainFrame::OnUpdateUIOptionsGenerate(wxUpdateUIEvent& event)
{
event.Check(fGenerateBitcoins);
}
void CMainFrame::OnMenuOptionsChangeYourAddress(wxCommandEvent& event)
{
// Options->Your Receiving Addresses
CAddressBookDialog dialog(this, "", CAddressBookDialog::RECEIVING, false);
if (!dialog.ShowModal())
return;
}
void CMainFrame::OnMenuOptionsOptions(wxCommandEvent& event)
{
// Options->Options
COptionsDialog dialog(this);
dialog.ShowModal();
}
void CMainFrame::OnMenuHelpAbout(wxCommandEvent& event)
{
// Help->About
CAboutDialog dialog(this);
dialog.ShowModal();
}
void CMainFrame::OnButtonSend(wxCommandEvent& event)
{
// Toolbar: Send
CSendDialog dialog(this);
dialog.ShowModal();
}
void CMainFrame::OnButtonAddressBook(wxCommandEvent& event)
{
// Toolbar: Address Book
CAddressBookDialog dialogAddr(this, "", CAddressBookDialog::SENDING, false);
if (dialogAddr.ShowModal() == 2)
{
// Send
CSendDialog dialogSend(this, dialogAddr.GetSelectedAddress());
dialogSend.ShowModal();
}
}
void CMainFrame::OnSetFocusAddress(wxFocusEvent& event)
{
// Automatically select-all when entering window
event.Skip();
m_textCtrlAddress->SetSelection(-1, -1);
fOnSetFocusAddress = true;
}
void CMainFrame::OnMouseEventsAddress(wxMouseEvent& event)
{
event.Skip();
if (fOnSetFocusAddress)
m_textCtrlAddress->SetSelection(-1, -1);
fOnSetFocusAddress = false;
}
void CMainFrame::OnButtonNew(wxCommandEvent& event)
{
// Ask name
CGetTextFromUserDialog dialog(this,
_("New Receiving Address"),
_("You should use a new address for each payment you receive.\n\nLabel"),
"");
if (!dialog.ShowModal())
return;
string strName = dialog.GetValue();
// Generate new key
string strAddress = PubKeyToAddress(pwalletMain->GetKeyFromKeyPool());
// Save
- pwalletMain->SetAddressBookName(strAddress, strName);
+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
+ pwalletMain->SetAddressBookName(strAddress, strName);
SetDefaultReceivingAddress(strAddress);
}
void CMainFrame::OnButtonCopy(wxCommandEvent& event)
{
// Copy address box to clipboard
if (wxTheClipboard->Open())
{
wxTheClipboard->SetData(new wxTextDataObject(m_textCtrlAddress->GetValue()));
wxTheClipboard->Close();
}
}
void CMainFrame::OnListItemActivated(wxListEvent& event)
{
uint256 hash((string)GetItemText(m_listCtrl, event.GetIndex(), 1));
CWalletTx wtx;
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
if (mi == pwalletMain->mapWallet.end())
{
printf("CMainFrame::OnListItemActivated() : tx not found in mapWallet\n");
return;
}
wtx = (*mi).second;
}
CTxDetailsDialog dialog(this, wtx);
dialog.ShowModal();
//CTxDetailsDialog* pdialog = new CTxDetailsDialog(this, wtx);
//pdialog->Show();
}
//////////////////////////////////////////////////////////////////////////////
//
// CTxDetailsDialog
//
CTxDetailsDialog::CTxDetailsDialog(wxWindow* parent, CWalletTx wtx) : CTxDetailsDialogBase(parent)
{
#ifdef __WXMSW__
SetSize(nScaleX * GetSize().GetWidth(), nScaleY * GetSize().GetHeight());
#endif
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
string strHTML;
strHTML.reserve(4000);
strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";
int64 nTime = wtx.GetTxTime();
int64 nCredit = wtx.GetCredit();
int64 nDebit = wtx.GetDebit();
int64 nNet = nCredit - nDebit;
strHTML += _("<b>Status:</b> ") + FormatTxStatus(wtx);
int nRequests = wtx.GetRequestCount();
if (nRequests != -1)
{
if (nRequests == 0)
strHTML += _(", has not been successfully broadcast yet");
else if (nRequests == 1)
strHTML += strprintf(_(", broadcast through %d node"), nRequests);
else
strHTML += strprintf(_(", broadcast through %d nodes"), nRequests);
}
strHTML += "<br>";
strHTML += _("<b>Date:</b> ") + (nTime ? DateTimeStr(nTime) : "") + "<br>";
//
// From
//
if (wtx.IsCoinBase())
{
strHTML += _("<b>Source:</b> Generated<br>");
}
else if (!wtx.mapValue["from"].empty())
{
// Online transaction
if (!wtx.mapValue["from"].empty())
strHTML += _("<b>From:</b> ") + HtmlEscape(wtx.mapValue["from"]) + "<br>";
}
else
{
// Offline transaction
if (nNet > 0)
{
// Credit
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
if (pwalletMain->IsMine(txout))
{
vector<unsigned char> vchPubKey;
if (ExtractPubKey(txout.scriptPubKey, pwalletMain, vchPubKey))
{
string strAddress = PubKeyToAddress(vchPubKey);
if (pwalletMain->mapAddressBook.count(strAddress))
{
strHTML += string() + _("<b>From:</b> ") + _("unknown") + "<br>";
strHTML += _("<b>To:</b> ");
strHTML += HtmlEscape(strAddress);
if (!pwalletMain->mapAddressBook[strAddress].empty())
strHTML += _(" (yours, label: ") + pwalletMain->mapAddressBook[strAddress] + ")";
else
strHTML += _(" (yours)");
strHTML += "<br>";
}
}
break;
}
}
}
}
//
// To
//
string strAddress;
if (!wtx.mapValue["to"].empty())
{
// Online transaction
strAddress = wtx.mapValue["to"];
strHTML += _("<b>To:</b> ");
if (pwalletMain->mapAddressBook.count(strAddress) && !pwalletMain->mapAddressBook[strAddress].empty())
strHTML += pwalletMain->mapAddressBook[strAddress] + " ";
strHTML += HtmlEscape(strAddress) + "<br>";
}
//
// Amount
//
if (wtx.IsCoinBase() && nCredit == 0)
{
//
// Coinbase
//
int64 nUnmatured = 0;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
nUnmatured += pwalletMain->GetCredit(txout);
strHTML += _("<b>Credit:</b> ");
if (wtx.IsInMainChain())
strHTML += strprintf(_("(%s matures in %d more blocks)"), FormatMoney(nUnmatured).c_str(), wtx.GetBlocksToMaturity());
else
strHTML += _("(not accepted)");
strHTML += "<br>";
}
else if (nNet > 0)
{
//
// Credit
//
strHTML += _("<b>Credit:</b> ") + FormatMoney(nNet) + "<br>";
}
else
{
bool fAllFromMe = true;
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
fAllFromMe = fAllFromMe && pwalletMain->IsMine(txin);
bool fAllToMe = true;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
fAllToMe = fAllToMe && pwalletMain->IsMine(txout);
if (fAllFromMe)
{
//
// Debit
//
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
if (pwalletMain->IsMine(txout))
continue;
if (wtx.mapValue["to"].empty())
{
// Offline transaction
uint160 hash160;
if (ExtractHash160(txout.scriptPubKey, hash160))
{
string strAddress = Hash160ToAddress(hash160);
strHTML += _("<b>To:</b> ");
if (pwalletMain->mapAddressBook.count(strAddress) && !pwalletMain->mapAddressBook[strAddress].empty())
strHTML += pwalletMain->mapAddressBook[strAddress] + " ";
strHTML += strAddress;
strHTML += "<br>";
}
}
strHTML += _("<b>Debit:</b> ") + FormatMoney(-txout.nValue) + "<br>";
}
if (fAllToMe)
{
// Payment to self
int64 nChange = wtx.GetChange();
int64 nValue = nCredit - nChange;
strHTML += _("<b>Debit:</b> ") + FormatMoney(-nValue) + "<br>";
strHTML += _("<b>Credit:</b> ") + FormatMoney(nValue) + "<br>";
}
int64 nTxFee = nDebit - wtx.GetValueOut();
if (nTxFee > 0)
strHTML += _("<b>Transaction fee:</b> ") + FormatMoney(-nTxFee) + "<br>";
}
else
{
//
// Mixed debit transaction
//
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
if (pwalletMain->IsMine(txin))
strHTML += _("<b>Debit:</b> ") + FormatMoney(-pwalletMain->GetDebit(txin)) + "<br>";
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (pwalletMain->IsMine(txout))
strHTML += _("<b>Credit:</b> ") + FormatMoney(pwalletMain->GetCredit(txout)) + "<br>";
}
}
strHTML += _("<b>Net amount:</b> ") + FormatMoney(nNet, true) + "<br>";
//
// Message
//
if (!wtx.mapValue["message"].empty())
strHTML += string() + "<br><b>" + _("Message:") + "</b><br>" + HtmlEscape(wtx.mapValue["message"], true) + "<br>";
if (!wtx.mapValue["comment"].empty())
strHTML += string() + "<br><b>" + _("Comment:") + "</b><br>" + HtmlEscape(wtx.mapValue["comment"], true) + "<br>";
if (wtx.IsCoinBase())
strHTML += string() + "<br>" + _("Generated coins must wait 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, it will change to \"not accepted\" and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.") + "<br>";
//
// Debug view
//
if (fDebug)
{
strHTML += "<hr><br>debug print<br><br>";
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
if (pwalletMain->IsMine(txin))
strHTML += "<b>Debit:</b> " + FormatMoney(-pwalletMain->GetDebit(txin)) + "<br>";
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (pwalletMain->IsMine(txout))
strHTML += "<b>Credit:</b> " + FormatMoney(pwalletMain->GetCredit(txout)) + "<br>";
strHTML += "<br><b>Transaction:</b><br>";
strHTML += HtmlEscape(wtx.ToString(), true);
strHTML += "<br><b>Inputs:</b><br>";
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
COutPoint prevout = txin.prevout;
map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(prevout.hash);
if (mi != pwalletMain->mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (prevout.n < prev.vout.size())
{
strHTML += HtmlEscape(prev.ToString(), true);
strHTML += " &nbsp;&nbsp; " + FormatTxStatus(prev) + ", ";
strHTML = strHTML + "IsMine=" + (pwalletMain->IsMine(prev.vout[prevout.n]) ? "true" : "false") + "<br>";
}
}
}
}
}
strHTML += "</font></html>";
string(strHTML.begin(), strHTML.end()).swap(strHTML);
m_htmlWin->SetPage(strHTML);
m_buttonOK->SetFocus();
}
}
void CTxDetailsDialog::OnButtonOK(wxCommandEvent& event)
{
EndModal(false);
}
//////////////////////////////////////////////////////////////////////////////
//
// Startup folder
//
#ifdef __WXMSW__
string StartupShortcutPath()
{
return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";
}
bool GetStartOnSystemStartup()
{
return filesystem::exists(StartupShortcutPath().c_str());
}
void SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
remove(StartupShortcutPath().c_str());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
}
psl->Release();
}
CoUninitialize();
}
}
#elif defined(__WXGTK__)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / fs::path("autostart");
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / fs::path(".config/autostart");
return fs::path();
}
boost::filesystem::path GetAutostartFilePath()
{
return GetAutostartDir() / boost::filesystem::path("bitcoin.desktop");
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != string::npos &&
line.find("true") != string::npos)
return false;
}
optionFile.close();
return true;
}
void SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
{
unlink(GetAutostartFilePath().native_file_string().c_str());
}
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
if (!optionFile.good())
{
wxMessageBox(_("Cannot write autostart/bitcoin.desktop file"), "Bitcoin");
return;
}
// Write a bitcoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=Bitcoin\n";
optionFile << "Exec=" << pszExePath << "\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
}
#else
// TODO: OSX startup stuff; see:
// http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
bool GetStartOnSystemStartup() { return false; }
void SetStartOnSystemStartup(bool fAutoStart) { }
#endif
//////////////////////////////////////////////////////////////////////////////
//
// COptionsDialog
//
COptionsDialog::COptionsDialog(wxWindow* parent) : COptionsDialogBase(parent)
{
// Set up list box of page choices
m_listBox->Append(_("Main"));
//m_listBox->Append(_("Test 2"));
m_listBox->SetSelection(0);
SelectPage(0);
#ifndef __WXMSW__
SetSize(1.0 * GetSize().GetWidth(), 1.2 * GetSize().GetHeight());
#else
SetSize(nScaleX * GetSize().GetWidth(), nScaleY * GetSize().GetHeight());
#endif
#if defined(__WXGTK__) || defined(__WXMAC_OSX__)
m_checkBoxStartOnSystemStartup->SetLabel(_("&Start Bitcoin on window system startup"));
if (!GetBoolArg("-minimizetotray"))
{
// Minimize to tray is just too buggy on Linux
fMinimizeToTray = false;
m_checkBoxMinimizeToTray->SetValue(false);
m_checkBoxMinimizeToTray->Enable(false);
m_checkBoxMinimizeOnClose->SetLabel(_("&Minimize on close"));
}
#endif
#ifdef __WXMAC_OSX__
m_checkBoxStartOnSystemStartup->Enable(false); // not implemented yet
#endif
// Init values
m_textCtrlTransactionFee->SetValue(FormatMoney(nTransactionFee));
m_checkBoxStartOnSystemStartup->SetValue(fTmpStartOnSystemStartup = GetStartOnSystemStartup());
m_checkBoxMinimizeToTray->SetValue(fMinimizeToTray);
m_checkBoxMinimizeOnClose->SetValue(fMinimizeOnClose);
if (fHaveUPnP)
m_checkBoxUseUPnP->SetValue(fUseUPnP);
else
m_checkBoxUseUPnP->Enable(false);
m_checkBoxUseProxy->SetValue(fUseProxy);
m_textCtrlProxyIP->Enable(fUseProxy);
m_textCtrlProxyPort->Enable(fUseProxy);
m_staticTextProxyIP->Enable(fUseProxy);
m_staticTextProxyPort->Enable(fUseProxy);
m_textCtrlProxyIP->SetValue(addrProxy.ToStringIP());
m_textCtrlProxyPort->SetValue(addrProxy.ToStringPort());
m_buttonOK->SetFocus();
}
void COptionsDialog::SelectPage(int nPage)
{
m_panelMain->Show(nPage == 0);
m_panelTest2->Show(nPage == 1);
m_scrolledWindow->Layout();
m_scrolledWindow->SetScrollbars(0, 0, 0, 0, 0, 0);
}
void COptionsDialog::OnListBox(wxCommandEvent& event)
{
SelectPage(event.GetSelection());
}
void COptionsDialog::OnKillFocusTransactionFee(wxFocusEvent& event)
{
event.Skip();
int64 nTmp = nTransactionFee;
ParseMoney(m_textCtrlTransactionFee->GetValue(), nTmp);
m_textCtrlTransactionFee->SetValue(FormatMoney(nTmp));
}
void COptionsDialog::OnCheckBoxUseProxy(wxCommandEvent& event)
{
m_textCtrlProxyIP->Enable(event.IsChecked());
m_textCtrlProxyPort->Enable(event.IsChecked());
m_staticTextProxyIP->Enable(event.IsChecked());
m_staticTextProxyPort->Enable(event.IsChecked());
}
CAddress COptionsDialog::GetProxyAddr()
{
// Be careful about byte order, addr.ip and addr.port are big endian
CAddress addr(m_textCtrlProxyIP->GetValue() + ":" + m_textCtrlProxyPort->GetValue());
if (addr.ip == INADDR_NONE)
addr.ip = addrProxy.ip;
int nPort = atoi(m_textCtrlProxyPort->GetValue());
addr.port = htons(nPort);
if (nPort <= 0 || nPort > USHRT_MAX)
addr.port = addrProxy.port;
return addr;
}
void COptionsDialog::OnKillFocusProxy(wxFocusEvent& event)
{
event.Skip();
m_textCtrlProxyIP->SetValue(GetProxyAddr().ToStringIP());
m_textCtrlProxyPort->SetValue(GetProxyAddr().ToStringPort());
}
void COptionsDialog::OnButtonOK(wxCommandEvent& event)
{
OnButtonApply(event);
EndModal(false);
}
void COptionsDialog::OnButtonCancel(wxCommandEvent& event)
{
EndModal(false);
}
void COptionsDialog::OnButtonApply(wxCommandEvent& event)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
int64 nPrevTransactionFee = nTransactionFee;
if (ParseMoney(m_textCtrlTransactionFee->GetValue(), nTransactionFee) && nTransactionFee != nPrevTransactionFee)
walletdb.WriteSetting("nTransactionFee", nTransactionFee);
if (fTmpStartOnSystemStartup != m_checkBoxStartOnSystemStartup->GetValue())
{
fTmpStartOnSystemStartup = m_checkBoxStartOnSystemStartup->GetValue();
SetStartOnSystemStartup(fTmpStartOnSystemStartup);
}
if (fMinimizeToTray != m_checkBoxMinimizeToTray->GetValue())
{
fMinimizeToTray = m_checkBoxMinimizeToTray->GetValue();
walletdb.WriteSetting("fMinimizeToTray", fMinimizeToTray);
ptaskbaricon->Show(fMinimizeToTray || fClosedToTray);
}
if (fMinimizeOnClose != m_checkBoxMinimizeOnClose->GetValue())
{
fMinimizeOnClose = m_checkBoxMinimizeOnClose->GetValue();
walletdb.WriteSetting("fMinimizeOnClose", fMinimizeOnClose);
}
if (fHaveUPnP && fUseUPnP != m_checkBoxUseUPnP->GetValue())
{
fUseUPnP = m_checkBoxUseUPnP->GetValue();
walletdb.WriteSetting("fUseUPnP", fUseUPnP);
MapPort(fUseUPnP);
}
fUseProxy = m_checkBoxUseProxy->GetValue();
walletdb.WriteSetting("fUseProxy", fUseProxy);
addrProxy = GetProxyAddr();
walletdb.WriteSetting("addrProxy", addrProxy);
}
//////////////////////////////////////////////////////////////////////////////
//
// CAboutDialog
//
CAboutDialog::CAboutDialog(wxWindow* parent) : CAboutDialogBase(parent)
{
m_staticTextVersion->SetLabel(strprintf(_("version %s"), FormatFullVersion().c_str()));
// Change (c) into UTF-8 or ANSI copyright symbol
wxString str = m_staticTextMain->GetLabel();
#if wxUSE_UNICODE
str.Replace("(c)", wxString::FromUTF8("\xC2\xA9"));
#else
str.Replace("(c)", "\xA9");
#endif
m_staticTextMain->SetLabel(str);
#ifndef __WXMSW__
// Resize on Linux to make the window fit the text.
// The text was wrapped manually rather than using the Wrap setting because
// the wrap would be too small on Linux and it can't be changed at this point.
wxFont fontTmp = m_staticTextMain->GetFont();
if (fontTmp.GetPointSize() > 8);
fontTmp.SetPointSize(8);
m_staticTextMain->SetFont(fontTmp);
SetSize(GetSize().GetWidth() + 44, GetSize().GetHeight() + 10);
#else
SetSize(nScaleX * GetSize().GetWidth(), nScaleY * GetSize().GetHeight());
#endif
}
void CAboutDialog::OnButtonOK(wxCommandEvent& event)
{
EndModal(false);
}
//////////////////////////////////////////////////////////////////////////////
//
// CSendDialog
//
CSendDialog::CSendDialog(wxWindow* parent, const wxString& strAddress) : CSendDialogBase(parent)
{
// Init
m_textCtrlAddress->SetValue(strAddress);
m_choiceTransferType->SetSelection(0);
m_bitmapCheckMark->Show(false);
fEnabledPrev = true;
m_textCtrlAddress->SetFocus();
//// todo: should add a display of your balance for convenience
#ifndef __WXMSW__
wxFont fontTmp = m_staticTextInstructions->GetFont();
if (fontTmp.GetPointSize() > 9);
fontTmp.SetPointSize(9);
m_staticTextInstructions->SetFont(fontTmp);
SetSize(725, 180);
#else
SetSize(nScaleX * GetSize().GetWidth(), nScaleY * GetSize().GetHeight());
#endif
// Set Icon
if (nScaleX == 1.0 && nScaleY == 1.0) // We don't have icons of the proper size otherwise
{
wxIcon iconSend;
iconSend.CopyFromBitmap(wxBitmap(send16noshadow_xpm));
SetIcon(iconSend);
}
#ifdef __WXMSW__
else
SetIcon(wxICON(bitcoin));
#endif
// Fixup the tab order
m_buttonPaste->MoveAfterInTabOrder(m_buttonCancel);
m_buttonAddress->MoveAfterInTabOrder(m_buttonPaste);
this->Layout();
}
void CSendDialog::OnKillFocusAmount(wxFocusEvent& event)
{
// Reformat the amount
event.Skip();
if (m_textCtrlAmount->GetValue().Trim().empty())
return;
int64 nTmp;
if (ParseMoney(m_textCtrlAmount->GetValue(), nTmp))
m_textCtrlAmount->SetValue(FormatMoney(nTmp));
}
void CSendDialog::OnButtonAddressBook(wxCommandEvent& event)
{
// Open address book
CAddressBookDialog dialog(this, m_textCtrlAddress->GetValue(), CAddressBookDialog::SENDING, true);
if (dialog.ShowModal())
m_textCtrlAddress->SetValue(dialog.GetSelectedAddress());
}
void CSendDialog::OnButtonPaste(wxCommandEvent& event)
{
// Copy clipboard to address box
if (wxTheClipboard->Open())
{
if (wxTheClipboard->IsSupported(wxDF_TEXT))
{
wxTextDataObject data;
wxTheClipboard->GetData(data);
m_textCtrlAddress->SetValue(data.GetText());
}
wxTheClipboard->Close();
}
}
void CSendDialog::OnButtonSend(wxCommandEvent& event)
{
static CCriticalSection cs_sendlock;
TRY_CRITICAL_BLOCK(cs_sendlock)
{
CWalletTx wtx;
string strAddress = (string)m_textCtrlAddress->GetValue();
// Parse amount
int64 nValue = 0;
if (!ParseMoney(m_textCtrlAmount->GetValue(), nValue) || nValue <= 0)
{
wxMessageBox(_("Error in amount "), _("Send Coins"));
return;
}
if (nValue > pwalletMain->GetBalance())
{
wxMessageBox(_("Amount exceeds your balance "), _("Send Coins"));
return;
}
if (nValue + nTransactionFee > pwalletMain->GetBalance())
{
wxMessageBox(string(_("Total exceeds your balance when the ")) + FormatMoney(nTransactionFee) + _(" transaction fee is included "), _("Send Coins"));
return;
}
// Parse bitcoin address
uint160 hash160;
bool fBitcoinAddress = AddressToHash160(strAddress, hash160);
if (fBitcoinAddress)
{
CRITICAL_BLOCK(cs_main)
{
// Send to bitcoin address
CScript scriptPubKey;
scriptPubKey << OP_DUP << OP_HASH160 << hash160 << OP_EQUALVERIFY << OP_CHECKSIG;
string strError = pwalletMain->SendMoney(scriptPubKey, nValue, wtx, true);
if (strError == "")
wxMessageBox(_("Payment sent "), _("Sending..."));
else if (strError == "ABORTED")
return; // leave send dialog open
else
{
wxMessageBox(strError + " ", _("Sending..."));
EndModal(false);
return;
}
}
}
else
{
// Parse IP address
CAddress addr(strAddress);
if (!addr.IsValid())
{
wxMessageBox(_("Invalid address "), _("Send Coins"));
return;
}
// Message
wtx.mapValue["to"] = strAddress;
// Send to IP address
CSendingDialog* pdialog = new CSendingDialog(this, addr, nValue, wtx);
if (!pdialog->ShowModal())
return;
}
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
if (!pwalletMain->mapAddressBook.count(strAddress))
pwalletMain->SetAddressBookName(strAddress, "");
EndModal(true);
}
}
void CSendDialog::OnButtonCancel(wxCommandEvent& event)
{
// Cancel
EndModal(false);
}
//////////////////////////////////////////////////////////////////////////////
//
// CSendingDialog
//
CSendingDialog::CSendingDialog(wxWindow* parent, const CAddress& addrIn, int64 nPriceIn, const CWalletTx& wtxIn) : CSendingDialogBase(NULL) // we have to give null so parent can't destroy us
{
addr = addrIn;
nPrice = nPriceIn;
wtx = wtxIn;
start = wxDateTime::UNow();
memset(pszStatus, 0, sizeof(pszStatus));
fCanCancel = true;
fAbort = false;
fSuccess = false;
fUIDone = false;
fWorkDone = false;
#ifndef __WXMSW__
SetSize(1.2 * GetSize().GetWidth(), 1.08 * GetSize().GetHeight());
#else
SetSize(nScaleX * GetSize().GetWidth(), nScaleY * GetSize().GetHeight());
#endif
SetTitle(strprintf(_("Sending %s to %s"), FormatMoney(nPrice).c_str(), wtx.mapValue["to"].c_str()));
m_textCtrlStatus->SetValue("");
CreateThread(SendingDialogStartTransfer, this);
}
CSendingDialog::~CSendingDialog()
{
printf("~CSendingDialog()\n");
}
void CSendingDialog::Close()
{
// Last one out turn out the lights.
// fWorkDone signals that work side is done and UI thread should call destroy.
// fUIDone signals that UI window has closed and work thread should call destroy.
// This allows the window to disappear and end modality when cancelled
// without making the user wait for ConnectNode to return. The dialog object
// hangs around in the background until the work thread exits.
if (IsModal())
EndModal(fSuccess);
else
Show(false);
if (fWorkDone)
Destroy();
else
fUIDone = true;
}
void CSendingDialog::OnClose(wxCloseEvent& event)
{
if (!event.CanVeto() || fWorkDone || fAbort || !fCanCancel)
{
Close();
}
else
{
event.Veto();
wxCommandEvent cmdevent;
OnButtonCancel(cmdevent);
}
}
void CSendingDialog::OnButtonOK(wxCommandEvent& event)
{
if (fWorkDone)
Close();
}
void CSendingDialog::OnButtonCancel(wxCommandEvent& event)
{
if (fCanCancel)
fAbort = true;
}
void CSendingDialog::OnPaint(wxPaintEvent& event)
{
event.Skip();
if (strlen(pszStatus) > 130)
m_textCtrlStatus->SetValue(string("\n") + pszStatus);
else
m_textCtrlStatus->SetValue(string("\n\n") + pszStatus);
m_staticTextSending->SetFocus();
if (!fCanCancel)
m_buttonCancel->Enable(false);
if (fWorkDone)
{
m_buttonOK->Enable(true);
m_buttonOK->SetFocus();
m_buttonCancel->Enable(false);
}
if (fAbort && fCanCancel && IsShown())
{
strcpy(pszStatus, _("CANCELLED"));
m_buttonOK->Enable(true);
m_buttonOK->SetFocus();
m_buttonCancel->Enable(false);
m_buttonCancel->SetLabel(_("Cancelled"));
Close();
wxMessageBox(_("Transfer cancelled "), _("Sending..."), wxOK, this);
}
}
//
// Everything from here on is not in the UI thread and must only communicate
// with the rest of the dialog through variables and calling repaint.
//
void CSendingDialog::Repaint()
{
Refresh();
wxPaintEvent event;
GetEventHandler()->AddPendingEvent(event);
}
bool CSendingDialog::Status()
{
if (fUIDone)
{
Destroy();
return false;
}
if (fAbort && fCanCancel)
{
memset(pszStatus, 0, 10);
strcpy(pszStatus, _("CANCELLED"));
Repaint();
fWorkDone = true;
return false;
}
return true;
}
bool CSendingDialog::Status(const string& str)
{
if (!Status())
return false;
// This can be read by the UI thread at any time,
// so copy in a way that can be read cleanly at all times.
memset(pszStatus, 0, min(str.size()+1, sizeof(pszStatus)));
strlcpy(pszStatus, str.c_str(), sizeof(pszStatus));
Repaint();
return true;
}
bool CSendingDialog::Error(const string& str)
{
fCanCancel = false;
fWorkDone = true;
Status(string(_("Error: ")) + str);
return false;
}
void SendingDialogStartTransfer(void* parg)
{
((CSendingDialog*)parg)->StartTransfer();
}
void CSendingDialog::StartTransfer()
{
// Make sure we have enough money
if (nPrice + nTransactionFee > pwalletMain->GetBalance())
{
Error(_("Insufficient funds"));
return;
}
// We may have connected already for product details
if (!Status(_("Connecting...")))
return;
CNode* pnode = ConnectNode(addr, 15 * 60);
if (!pnode)
{
Error(_("Unable to connect"));
return;
}
// Send order to seller, with response going to OnReply2 via event handler
if (!Status(_("Requesting public key...")))
return;
pnode->PushRequest("checkorder", wtx, SendingDialogOnReply2, this);
}
void SendingDialogOnReply2(void* parg, CDataStream& vRecv)
{
((CSendingDialog*)parg)->OnReply2(vRecv);
}
void CSendingDialog::OnReply2(CDataStream& vRecv)
{
if (!Status(_("Received public key...")))
return;
CScript scriptPubKey;
int nRet;
try
{
vRecv >> nRet;
if (nRet > 0)
{
string strMessage;
if (!vRecv.empty())
vRecv >> strMessage;
if (nRet == 2)
Error(_("Recipient is not accepting transactions sent by IP address"));
else
Error(_("Transfer was not accepted"));
//// todo: enlarge the window and enable a hidden white box to put seller's message
return;
}
vRecv >> scriptPubKey;
}
catch (...)
{
//// what do we want to do about this?
Error(_("Invalid response received"));
return;
}
// Pause to give the user a chance to cancel
while (wxDateTime::UNow() < start + wxTimeSpan(0, 0, 0, 2 * 1000))
{
Sleep(200);
if (!Status())
return;
}
CRITICAL_BLOCK(cs_main)
{
// Pay
if (!Status(_("Creating transaction...")))
return;
if (nPrice + nTransactionFee > pwalletMain->GetBalance())
{
Error(_("Insufficient funds"));
return;
}
CReserveKey reservekey(pwalletMain);
int64 nFeeRequired;
if (!pwalletMain->CreateTransaction(scriptPubKey, nPrice, wtx, reservekey, nFeeRequired))
{
if (nPrice + nFeeRequired > pwalletMain->GetBalance())
Error(strprintf(_("This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds"), FormatMoney(nFeeRequired).c_str()));
else
Error(_("Transaction creation failed"));
return;
}
// Transaction fee
if (!ThreadSafeAskFee(nFeeRequired, _("Sending..."), this))
{
Error(_("Transaction aborted"));
return;
}
// Make sure we're still connected
CNode* pnode = ConnectNode(addr, 2 * 60 * 60);
if (!pnode)
{
Error(_("Lost connection, transaction cancelled"));
return;
}
// Last chance to cancel
Sleep(50);
if (!Status())
return;
fCanCancel = false;
if (fAbort)
{
fCanCancel = true;
if (!Status())
return;
fCanCancel = false;
}
if (!Status(_("Sending payment...")))
return;
// Commit
if (!pwalletMain->CommitTransaction(wtx, reservekey))
{
Error(_("The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."));
return;
}
// Send payment tx to seller, with response going to OnReply3 via event handler
CWalletTx wtxSend = wtx;
wtxSend.fFromMe = false;
pnode->PushRequest("submitorder", wtxSend, SendingDialogOnReply3, this);
Status(_("Waiting for confirmation..."));
MainFrameRepaint();
}
}
void SendingDialogOnReply3(void* parg, CDataStream& vRecv)
{
((CSendingDialog*)parg)->OnReply3(vRecv);
}
void CSendingDialog::OnReply3(CDataStream& vRecv)
{
int nRet;
try
{
vRecv >> nRet;
if (nRet > 0)
{
Error(_("The payment was sent, but the recipient was unable to verify it.\n"
"The transaction is recorded and will credit to the recipient,\n"
"but the comment information will be blank."));
return;
}
}
catch (...)
{
//// what do we want to do about this?
Error(_("Payment was sent, but an invalid response was received"));
return;
}
fSuccess = true;
fWorkDone = true;
Status(_("Payment completed"));
}
//////////////////////////////////////////////////////////////////////////////
//
// CAddressBookDialog
//
CAddressBookDialog::CAddressBookDialog(wxWindow* parent, const wxString& strInitSelected, int nPageIn, bool fDuringSendIn) : CAddressBookDialogBase(parent)
{
#ifdef __WXMSW__
SetSize(nScaleX * GetSize().GetWidth(), nScaleY * GetSize().GetHeight());
#endif
// Set initially selected page
wxNotebookEvent event;
event.SetSelection(nPageIn);
OnNotebookPageChanged(event);
m_notebook->ChangeSelection(nPageIn);
fDuringSend = fDuringSendIn;
if (!fDuringSend)
m_buttonCancel->Show(false);
// Set Icon
if (nScaleX == 1.0 && nScaleY == 1.0) // We don't have icons of the proper size otherwise
{
wxIcon iconAddressBook;
iconAddressBook.CopyFromBitmap(wxBitmap(addressbook16_xpm));
SetIcon(iconAddressBook);
}
#ifdef __WXMSW__
else
SetIcon(wxICON(bitcoin));
#endif
// Init column headers
m_listCtrlSending->InsertColumn(0, _("Name"), wxLIST_FORMAT_LEFT, 200);
m_listCtrlSending->InsertColumn(1, _("Address"), wxLIST_FORMAT_LEFT, 350);
m_listCtrlSending->SetFocus();
m_listCtrlReceiving->InsertColumn(0, _("Label"), wxLIST_FORMAT_LEFT, 200);
m_listCtrlReceiving->InsertColumn(1, _("Bitcoin Address"), wxLIST_FORMAT_LEFT, 350);
m_listCtrlReceiving->SetFocus();
// Fill listctrl with address book data
CRITICAL_BLOCK(pwalletMain->cs_mapKeys)
CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
{
string strDefaultReceiving = (string)pframeMain->m_textCtrlAddress->GetValue();
BOOST_FOREACH(const PAIRTYPE(string, string)& item, pwalletMain->mapAddressBook)
{
string strAddress = item.first;
string strName = item.second;
uint160 hash160;
bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160));
wxListCtrl* plistCtrl = fMine ? m_listCtrlReceiving : m_listCtrlSending;
int nIndex = InsertLine(plistCtrl, strName, strAddress);
if (strAddress == (fMine ? strDefaultReceiving : string(strInitSelected)))
plistCtrl->SetItemState(nIndex, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED, wxLIST_STATE_SELECTED|wxLIST_STATE_FOCUSED);
}
}
}
wxString CAddressBookDialog::GetSelectedAddress()
{
int nIndex = GetSelection(m_listCtrl);
if (nIndex == -1)
return "";
return GetItemText(m_listCtrl, nIndex, 1);
}
wxString CAddressBookDialog::GetSelectedSendingAddress()
{
int nIndex = GetSelection(m_listCtrlSending);
if (nIndex == -1)
return "";
return GetItemText(m_listCtrlSending, nIndex, 1);
}
wxString CAddressBookDialog::GetSelectedReceivingAddress()
{
int nIndex = GetSelection(m_listCtrlReceiving);
if (nIndex == -1)
return "";
return GetItemText(m_listCtrlReceiving, nIndex, 1);
}
void CAddressBookDialog::OnNotebookPageChanged(wxNotebookEvent& event)
{
event.Skip();
nPage = event.GetSelection();
if (nPage == SENDING)
m_listCtrl = m_listCtrlSending;
else if (nPage == RECEIVING)
m_listCtrl = m_listCtrlReceiving;
m_buttonDelete->Show(nPage == SENDING);
m_buttonCopy->Show(nPage == RECEIVING);
this->Layout();
m_listCtrl->SetFocus();
}
void CAddressBookDialog::OnListEndLabelEdit(wxListEvent& event)
{
// Update address book with edited name
event.Skip();
if (event.IsEditCancelled())
return;
string strAddress = (string)GetItemText(m_listCtrl, event.GetIndex(), 1);
- pwalletMain->SetAddressBookName(strAddress, string(event.GetText()));
+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
+ pwalletMain->SetAddressBookName(strAddress, string(event.GetText()));
pframeMain->RefreshListCtrl();
}
void CAddressBookDialog::OnListItemSelected(wxListEvent& event)
{
event.Skip();
if (nPage == RECEIVING)
SetDefaultReceivingAddress((string)GetSelectedReceivingAddress());
}
void CAddressBookDialog::OnListItemActivated(wxListEvent& event)
{
event.Skip();
if (fDuringSend)
{
// Doubleclick returns selection
EndModal(GetSelectedAddress() != "" ? 2 : 0);
return;
}
// Doubleclick edits item
wxCommandEvent event2;
OnButtonEdit(event2);
}
void CAddressBookDialog::OnButtonDelete(wxCommandEvent& event)
{
if (nPage != SENDING)
return;
for (int nIndex = m_listCtrl->GetItemCount()-1; nIndex >= 0; nIndex--)
{
if (m_listCtrl->GetItemState(nIndex, wxLIST_STATE_SELECTED))
{
string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);
- CWalletDB(pwalletMain->strWalletFile).EraseName(strAddress);
+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
+ pwalletMain->DelAddressBookName(strAddress);
m_listCtrl->DeleteItem(nIndex);
}
}
pframeMain->RefreshListCtrl();
}
void CAddressBookDialog::OnButtonCopy(wxCommandEvent& event)
{
// Copy address box to clipboard
if (wxTheClipboard->Open())
{
wxTheClipboard->SetData(new wxTextDataObject(GetSelectedAddress()));
wxTheClipboard->Close();
}
}
bool CAddressBookDialog::CheckIfMine(const string& strAddress, const string& strTitle)
{
uint160 hash160;
bool fMine = (AddressToHash160(strAddress, hash160) && mapPubKeys.count(hash160));
if (fMine)
wxMessageBox(_("This is one of your own addresses for receiving payments and cannot be entered in the address book. "), strTitle);
return fMine;
}
void CAddressBookDialog::OnButtonEdit(wxCommandEvent& event)
{
int nIndex = GetSelection(m_listCtrl);
if (nIndex == -1)
return;
string strName = (string)m_listCtrl->GetItemText(nIndex);
string strAddress = (string)GetItemText(m_listCtrl, nIndex, 1);
string strAddressOrg = strAddress;
if (nPage == SENDING)
{
// Ask name and address
do
{
CGetTextFromUserDialog dialog(this, _("Edit Address"), _("Name"), strName, _("Address"), strAddress);
if (!dialog.ShowModal())
return;
strName = dialog.GetValue1();
strAddress = dialog.GetValue2();
}
while (CheckIfMine(strAddress, _("Edit Address")));
}
else if (nPage == RECEIVING)
{
// Ask name
CGetTextFromUserDialog dialog(this, _("Edit Address Label"), _("Label"), strName);
if (!dialog.ShowModal())
return;
strName = dialog.GetValue();
}
// Write back
- if (strAddress != strAddressOrg)
- CWalletDB(pwalletMain->strWalletFile).EraseName(strAddressOrg);
- pwalletMain->SetAddressBookName(strAddress, strName);
+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
+ {
+ if (strAddress != strAddressOrg)
+ pwalletMain->DelAddressBookName(strAddressOrg);
+ pwalletMain->SetAddressBookName(strAddress, strName);
+ }
m_listCtrl->SetItem(nIndex, 1, strAddress);
m_listCtrl->SetItemText(nIndex, strName);
pframeMain->RefreshListCtrl();
}
void CAddressBookDialog::OnButtonNew(wxCommandEvent& event)
{
string strName;
string strAddress;
if (nPage == SENDING)
{
// Ask name and address
do
{
CGetTextFromUserDialog dialog(this, _("Add Address"), _("Name"), strName, _("Address"), strAddress);
if (!dialog.ShowModal())
return;
strName = dialog.GetValue1();
strAddress = dialog.GetValue2();
}
while (CheckIfMine(strAddress, _("Add Address")));
}
else if (nPage == RECEIVING)
{
// Ask name
CGetTextFromUserDialog dialog(this,
_("New Receiving Address"),
_("You should use a new address for each payment you receive.\n\nLabel"),
"");
if (!dialog.ShowModal())
return;
strName = dialog.GetValue();
// Generate new key
strAddress = PubKeyToAddress(pwalletMain->GetKeyFromKeyPool());
}
// Add to list and select it
- pwalletMain->SetAddressBookName(strAddress, strName);
+ CRITICAL_BLOCK(pwalletMain->cs_mapAddressBook)
+ pwalletMain->SetAddressBookName(strAddress, strName);
int nIndex = InsertLine(m_listCtrl, strName, strAddress);
SetSelection(m_listCtrl, nIndex);
m_listCtrl->SetFocus();
if (nPage == SENDING)
pframeMain->RefreshListCtrl();
}
void CAddressBookDialog::OnButtonOK(wxCommandEvent& event)
{
// OK
EndModal(GetSelectedAddress() != "" ? 1 : 0);
}
void CAddressBookDialog::OnButtonCancel(wxCommandEvent& event)
{
// Cancel
EndModal(0);
}
void CAddressBookDialog::OnClose(wxCloseEvent& event)
{
// Close
EndModal(0);
}
//////////////////////////////////////////////////////////////////////////////
//
// CMyTaskBarIcon
//
enum
{
ID_TASKBAR_RESTORE = 10001,
ID_TASKBAR_SEND,
ID_TASKBAR_OPTIONS,
ID_TASKBAR_GENERATE,
ID_TASKBAR_EXIT,
};
BEGIN_EVENT_TABLE(CMyTaskBarIcon, wxTaskBarIcon)
EVT_TASKBAR_LEFT_DCLICK(CMyTaskBarIcon::OnLeftButtonDClick)
EVT_MENU(ID_TASKBAR_RESTORE, CMyTaskBarIcon::OnMenuRestore)
EVT_MENU(ID_TASKBAR_SEND, CMyTaskBarIcon::OnMenuSend)
EVT_MENU(ID_TASKBAR_OPTIONS, CMyTaskBarIcon::OnMenuOptions)
EVT_UPDATE_UI(ID_TASKBAR_GENERATE, CMyTaskBarIcon::OnUpdateUIGenerate)
EVT_MENU(ID_TASKBAR_EXIT, CMyTaskBarIcon::OnMenuExit)
END_EVENT_TABLE()
void CMyTaskBarIcon::Show(bool fShow)
{
static char pszPrevTip[200];
if (fShow)
{
string strTooltip = _("Bitcoin");
if (fGenerateBitcoins)
strTooltip = _("Bitcoin - Generating");
if (fGenerateBitcoins && vNodes.empty())
strTooltip = _("Bitcoin - (not connected)");
// Optimization, only update when changed, using char array to be reentrant
if (strncmp(pszPrevTip, strTooltip.c_str(), sizeof(pszPrevTip)-1) != 0)
{
strlcpy(pszPrevTip, strTooltip.c_str(), sizeof(pszPrevTip));
#ifdef __WXMSW__
// somehow it'll choose the wrong size and scale it down if
// we use the main icon, so we hand it one with only 16x16
SetIcon(wxICON(favicon), strTooltip);
#else
SetIcon(bitcoin80_xpm, strTooltip);
#endif
}
}
else
{
strlcpy(pszPrevTip, "", sizeof(pszPrevTip));
RemoveIcon();
}
}
void CMyTaskBarIcon::Hide()
{
Show(false);
}
void CMyTaskBarIcon::OnLeftButtonDClick(wxTaskBarIconEvent& event)
{
Restore();
}
void CMyTaskBarIcon::OnMenuRestore(wxCommandEvent& event)
{
Restore();
}
void CMyTaskBarIcon::OnMenuSend(wxCommandEvent& event)
{
// Taskbar: Send
CSendDialog dialog(pframeMain);
dialog.ShowModal();
}
void CMyTaskBarIcon::OnMenuOptions(wxCommandEvent& event)
{
// Since it's modal, get the main window to do it
wxCommandEvent event2(wxEVT_COMMAND_MENU_SELECTED, wxID_PREFERENCES);
pframeMain->GetEventHandler()->AddPendingEvent(event2);
}
void CMyTaskBarIcon::Restore()
{
pframeMain->Show();
wxIconizeEvent event(0, false);
pframeMain->GetEventHandler()->AddPendingEvent(event);
pframeMain->Iconize(false);
pframeMain->Raise();
}
void CMyTaskBarIcon::OnUpdateUIGenerate(wxUpdateUIEvent& event)
{
event.Check(fGenerateBitcoins);
}
void CMyTaskBarIcon::OnMenuExit(wxCommandEvent& event)
{
pframeMain->Close(true);
}
void CMyTaskBarIcon::UpdateTooltip()
{
if (IsIconInstalled())
Show(true);
}
wxMenu* CMyTaskBarIcon::CreatePopupMenu()
{
wxMenu* pmenu = new wxMenu;
pmenu->Append(ID_TASKBAR_RESTORE, _("&Open Bitcoin"));
pmenu->Append(ID_TASKBAR_SEND, _("&Send Bitcoins"));
pmenu->Append(ID_TASKBAR_OPTIONS, _("O&ptions..."));
#ifndef __WXMAC_OSX__ // Mac has built-in quit menu
pmenu->AppendSeparator();
pmenu->Append(ID_TASKBAR_EXIT, _("E&xit"));
#endif
return pmenu;
}
//////////////////////////////////////////////////////////////////////////////
//
// CMyApp
//
void CreateMainWindow()
{
pframeMain = new CMainFrame(NULL);
if (GetBoolArg("-min"))
pframeMain->Iconize(true);
#if defined(__WXGTK__) || defined(__WXMAC_OSX__)
if (!GetBoolArg("-minimizetotray"))
fMinimizeToTray = false;
#endif
pframeMain->Show(true); // have to show first to get taskbar button to hide
if (fMinimizeToTray && pframeMain->IsIconized())
fClosedToTray = true;
pframeMain->Show(!fClosedToTray);
ptaskbaricon->Show(fMinimizeToTray || fClosedToTray);
CreateThread(ThreadDelayedRepaint, NULL);
}
// Define a new application
class CMyApp : public wxApp
{
public:
CMyApp(){};
~CMyApp(){};
bool OnInit();
bool OnInit2();
int OnExit();
// Hook Initialize so we can start without GUI
virtual bool Initialize(int& argc, wxChar** argv);
// 2nd-level exception handling: we get all the exceptions occurring in any
// event handler here
virtual bool OnExceptionInMainLoop();
// 3rd, and final, level exception handling: whenever an unhandled
// exception is caught, this function is called
virtual void OnUnhandledException();
// and now for something different: this function is called in case of a
// crash (e.g. dereferencing null pointer, division by 0, ...)
virtual void OnFatalException();
};
IMPLEMENT_APP(CMyApp)
bool CMyApp::Initialize(int& argc, wxChar** argv)
{
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]))
fCommandLine = true;
if (!fCommandLine)
{
// wxApp::Initialize will remove environment-specific parameters,
// so it's too early to call ParseParameters yet
for (int i = 1; i < argc; i++)
{
wxString str = argv[i];
#ifdef __WXMSW__
if (str.size() >= 1 && str[0] == '/')
str[0] = '-';
char pszLower[MAX_PATH];
strlcpy(pszLower, str.c_str(), sizeof(pszLower));
strlwr(pszLower);
str = pszLower;
#endif
if (str == "-daemon")
fDaemon = true;
}
}
#ifdef __WXGTK__
if (fDaemon || fCommandLine)
{
// Call the original Initialize while suppressing error messages
// and ignoring failure. If unable to initialize GTK, it fails
// near the end so hopefully the last few things don't matter.
{
wxLogNull logNo;
wxApp::Initialize(argc, argv);
}
if (fDaemon)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0)
pthread_exit((void*)0);
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
return true;
}
#endif
return wxApp::Initialize(argc, argv);
}
bool CMyApp::OnInit()
{
#if defined(__WXMSW__) && defined(__WXDEBUG__) && defined(GUI)
// Disable malfunctioning wxWidgets debug assertion
extern int g_isPainting;
g_isPainting = 10000;
#endif
#if defined(__WXMSW__ ) || defined(__WXMAC_OSX__)
SetAppName("Bitcoin");
#else
SetAppName("bitcoin");
#endif
#ifdef __WXMSW__
#if wxUSE_UNICODE
// Hack to set wxConvLibc codepage to UTF-8 on Windows,
// may break if wxMBConv_win32 implementation in strconv.cpp changes.
class wxMBConv_win32 : public wxMBConv
{
public:
long m_CodePage;
size_t m_minMBCharWidth;
};
if (((wxMBConv_win32*)&wxConvLibc)->m_CodePage == CP_ACP)
((wxMBConv_win32*)&wxConvLibc)->m_CodePage = CP_UTF8;
#endif
#endif
// Load locale/<lang>/LC_MESSAGES/bitcoin.mo language file
g_locale.Init(wxLANGUAGE_DEFAULT, 0);
g_locale.AddCatalogLookupPathPrefix("locale");
#ifndef __WXMSW__
g_locale.AddCatalogLookupPathPrefix("/usr/share/locale");
g_locale.AddCatalogLookupPathPrefix("/usr/local/share/locale");
#endif
g_locale.AddCatalog("wxstd"); // wxWidgets standard translations, if any
g_locale.AddCatalog("bitcoin");
#ifdef __WXMSW__
HDC hdc = GetDC(NULL);
if (hdc)
{
nScaleX = GetDeviceCaps(hdc, LOGPIXELSX) / 96.0;
nScaleY = GetDeviceCaps(hdc, LOGPIXELSY) / 96.0;
ReleaseDC(NULL, hdc);
}
#endif
return AppInit(argc, argv);
}
int CMyApp::OnExit()
{
Shutdown(NULL);
return wxApp::OnExit();
}
bool CMyApp::OnExceptionInMainLoop()
{
try
{
throw;
}
catch (std::exception& e)
{
PrintException(&e, "CMyApp::OnExceptionInMainLoop()");
wxLogWarning("Exception %s %s", typeid(e).name(), e.what());
Sleep(1000);
throw;
}
catch (...)
{
PrintException(NULL, "CMyApp::OnExceptionInMainLoop()");
wxLogWarning("Unknown exception");
Sleep(1000);
throw;
}
return true;
}
void CMyApp::OnUnhandledException()
{
// this shows how we may let some exception propagate uncaught
try
{
throw;
}
catch (std::exception& e)
{
PrintException(&e, "CMyApp::OnUnhandledException()");
wxLogWarning("Exception %s %s", typeid(e).name(), e.what());
Sleep(1000);
throw;
}
catch (...)
{
PrintException(NULL, "CMyApp::OnUnhandledException()");
wxLogWarning("Unknown exception");
Sleep(1000);
throw;
}
}
void CMyApp::OnFatalException()
{
wxMessageBox(_("Program has crashed and will terminate. "), "Bitcoin", wxOK | wxICON_ERROR);
}
diff --git a/src/wallet.cpp b/src/wallet.cpp
index e35bce61e..e54bbb3f4 100644
--- a/src/wallet.cpp
+++ b/src/wallet.cpp
@@ -1,1117 +1,1135 @@
// Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "headers.h"
#include "db.h"
#include "cryptopp/sha.h"
using namespace std;
//////////////////////////////////////////////////////////////////////////////
//
// mapWallet
//
bool CWallet::AddKey(const CKey& key)
{
this->CKeyStore::AddKey(key);
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey());
}
void CWallet::WalletUpdateSpent(const CTransaction &tx)
{
// Anytime a signature is successfully verified, it's proof the outpoint is spent.
// Update the wallet spent flag if it doesn't know due to wallet.dat being
// restored from backup or the user making copies of wallet.dat.
CRITICAL_BLOCK(cs_mapWallet)
{
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
CWalletTx& wtx = (*mi).second;
if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
{
printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
wtx.MarkSpent(txin.prevout.n);
wtx.WriteToDisk();
vWalletUpdated.push_back(txin.prevout.hash);
}
}
}
}
}
bool CWallet::AddToWallet(const CWalletTx& wtxIn)
{
uint256 hash = wtxIn.GetHash();
CRITICAL_BLOCK(cs_mapWallet)
{
// Inserts only if not already there, returns tx inserted or tx found
pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
CWalletTx& wtx = (*ret.first).second;
wtx.pwallet = this;
bool fInsertedNew = ret.second;
if (fInsertedNew)
wtx.nTimeReceived = GetAdjustedTime();
bool fUpdated = false;
if (!fInsertedNew)
{
// Merge
if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
{
wtx.hashBlock = wtxIn.hashBlock;
fUpdated = true;
}
if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
{
wtx.vMerkleBranch = wtxIn.vMerkleBranch;
wtx.nIndex = wtxIn.nIndex;
fUpdated = true;
}
if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
{
wtx.fFromMe = wtxIn.fFromMe;
fUpdated = true;
}
fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
}
//// debug print
printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
// Write to disk
if (fInsertedNew || fUpdated)
if (!wtx.WriteToDisk())
return false;
// If default receiving address gets used, replace it with a new one
CScript scriptDefaultKey;
scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
if (txout.scriptPubKey == scriptDefaultKey)
{
if (!fFileBacked)
continue;
CWalletDB walletdb(strWalletFile);
vchDefaultKey = GetKeyFromKeyPool();
walletdb.WriteDefaultKey(vchDefaultKey);
walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
}
}
// Notify UI
vWalletUpdated.push_back(hash);
// since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
WalletUpdateSpent(wtx);
}
// Refresh UI
MainFrameRepaint();
return true;
}
bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
{
uint256 hash = tx.GetHash();
bool fExisted = mapWallet.count(hash);
if (fExisted && !fUpdate) return false;
if (fExisted || IsMine(tx) || IsFromMe(tx))
{
CWalletTx wtx(this,tx);
// Get merkle branch if transaction was found in a block
if (pblock)
wtx.SetMerkleBranch(pblock);
return AddToWallet(wtx);
}
else
WalletUpdateSpent(tx);
return false;
}
bool CWallet::EraseFromWallet(uint256 hash)
{
if (!fFileBacked)
return false;
CRITICAL_BLOCK(cs_mapWallet)
{
if (mapWallet.erase(hash))
CWalletDB(strWalletFile).EraseTx(hash);
}
return true;
}
bool CWallet::IsMine(const CTxIn &txin) const
{
CRITICAL_BLOCK(cs_mapWallet)
{
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size())
if (IsMine(prev.vout[txin.prevout.n]))
return true;
}
}
return false;
}
int64 CWallet::GetDebit(const CTxIn &txin) const
{
CRITICAL_BLOCK(cs_mapWallet)
{
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size())
if (IsMine(prev.vout[txin.prevout.n]))
return prev.vout[txin.prevout.n].nValue;
}
}
return 0;
}
int64 CWalletTx::GetTxTime() const
{
if (!fTimeReceivedIsTxTime && hashBlock != 0)
{
// If we did not receive the transaction directly, we rely on the block's
// time to figure out when it happened. We use the median over a range
// of blocks to try to filter out inaccurate block times.
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex)
return pindex->GetMedianTime();
}
}
return nTimeReceived;
}
int CWalletTx::GetRequestCount() const
{
// Returns -1 if it wasn't being tracked
int nRequests = -1;
CRITICAL_BLOCK(pwallet->cs_mapRequestCount)
{
if (IsCoinBase())
{
// Generated block
if (hashBlock != 0)
{
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
}
}
else
{
// Did anyone request this transaction?
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
if (mi != pwallet->mapRequestCount.end())
{
nRequests = (*mi).second;
// How about the block it's in?
if (nRequests == 0 && hashBlock != 0)
{
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
else
nRequests = 1; // If it's in someone else's block it must have got out
}
}
}
}
return nRequests;
}
void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string, int64> >& listReceived,
list<pair<string, int64> >& listSent, int64& nFee, string& strSentAccount) const
{
nGeneratedImmature = nGeneratedMature = nFee = 0;
listReceived.clear();
listSent.clear();
strSentAccount = strFromAccount;
if (IsCoinBase())
{
if (GetBlocksToMaturity() > 0)
nGeneratedImmature = pwallet->GetCredit(*this);
else
nGeneratedMature = GetCredit();
return;
}
// Compute fee:
int64 nDebit = GetDebit();
if (nDebit > 0) // debit>0 means we signed/sent this transaction
{
int64 nValueOut = GetValueOut();
nFee = nDebit - nValueOut;
}
// 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)
BOOST_FOREACH(const CTxOut& txout, vout)
{
string address;
uint160 hash160;
vector<unsigned char> vchPubKey;
if (ExtractHash160(txout.scriptPubKey, hash160))
address = Hash160ToAddress(hash160);
else if (ExtractPubKey(txout.scriptPubKey, NULL, vchPubKey))
address = PubKeyToAddress(vchPubKey);
else
{
printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
this->GetHash().ToString().c_str());
address = " unknown ";
}
// Don't report 'change' txouts
if (nDebit > 0 && pwallet->IsChange(txout))
continue;
if (nDebit > 0)
listSent.push_back(make_pair(address, txout.nValue));
if (pwallet->IsMine(txout))
listReceived.push_back(make_pair(address, txout.nValue));
}
}
void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
int64& nSent, int64& nFee) const
{
nGenerated = nReceived = nSent = nFee = 0;
int64 allGeneratedImmature, allGeneratedMature, allFee;
allGeneratedImmature = allGeneratedMature = allFee = 0;
string strSentAccount;
list<pair<string, int64> > listReceived;
list<pair<string, int64> > listSent;
GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
if (strAccount == "")
nGenerated = allGeneratedMature;
if (strAccount == strSentAccount)
{
BOOST_FOREACH(const PAIRTYPE(string,int64)& s, listSent)
nSent += s.second;
nFee = allFee;
}
CRITICAL_BLOCK(pwallet->cs_mapAddressBook)
{
BOOST_FOREACH(const PAIRTYPE(string,int64)& r, listReceived)
{
if (pwallet->mapAddressBook.count(r.first))
{
map<string, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
nReceived += r.second;
}
else if (strAccount.empty())
{
nReceived += r.second;
}
}
}
}
void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
{
vtxPrev.clear();
const int COPY_DEPTH = 3;
if (SetMerkleBranch() < COPY_DEPTH)
{
vector<uint256> vWorkQueue;
BOOST_FOREACH(const CTxIn& txin, vin)
vWorkQueue.push_back(txin.prevout.hash);
// This critsect is OK because txdb is already open
CRITICAL_BLOCK(pwallet->cs_mapWallet)
{
map<uint256, const CMerkleTx*> mapWalletPrev;
set<uint256> setAlreadyDone;
for (int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hash = vWorkQueue[i];
if (setAlreadyDone.count(hash))
continue;
setAlreadyDone.insert(hash);
CMerkleTx tx;
map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
if (mi != pwallet->mapWallet.end())
{
tx = (*mi).second;
BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
}
else if (mapWalletPrev.count(hash))
{
tx = *mapWalletPrev[hash];
}
else if (!fClient && txdb.ReadDiskTx(hash, tx))
{
;
}
else
{
printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
continue;
}
int nDepth = tx.SetMerkleBranch();
vtxPrev.push_back(tx);
if (nDepth < COPY_DEPTH)
BOOST_FOREACH(const CTxIn& txin, tx.vin)
vWorkQueue.push_back(txin.prevout.hash);
}
}
}
reverse(vtxPrev.begin(), vtxPrev.end());
}
bool CWalletTx::WriteToDisk()
{
return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
}
int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
{
int ret = 0;
CBlockIndex* pindex = pindexStart;
CRITICAL_BLOCK(cs_mapWallet)
{
while (pindex)
{
CBlock block;
block.ReadFromDisk(pindex, true);
BOOST_FOREACH(CTransaction& tx, block.vtx)
{
if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
ret++;
}
pindex = pindex->pnext;
}
}
return ret;
}
void CWallet::ReacceptWalletTransactions()
{
CTxDB txdb("r");
bool fRepeat = true;
while (fRepeat) CRITICAL_BLOCK(cs_mapWallet)
{
fRepeat = false;
vector<CDiskTxPos> vMissingTx;
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{
CWalletTx& wtx = item.second;
if (wtx.IsCoinBase() && wtx.IsSpent(0))
continue;
CTxIndex txindex;
bool fUpdated = false;
if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
{
// Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
if (txindex.vSpent.size() != wtx.vout.size())
{
printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
continue;
}
for (int i = 0; i < txindex.vSpent.size(); i++)
{
if (wtx.IsSpent(i))
continue;
if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
{
wtx.MarkSpent(i);
fUpdated = true;
vMissingTx.push_back(txindex.vSpent[i]);
}
}
if (fUpdated)
{
printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
wtx.MarkDirty();
wtx.WriteToDisk();
}
}
else
{
// Reaccept any txes of ours that aren't already in a block
if (!wtx.IsCoinBase())
wtx.AcceptWalletTransaction(txdb, false);
}
}
if (!vMissingTx.empty())
{
// TODO: optimize this to scan just part of the block chain?
if (ScanForWalletTransactions(pindexGenesisBlock))
fRepeat = true; // Found missing transactions: re-do Reaccept.
}
}
}
void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
{
BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
{
if (!tx.IsCoinBase())
{
uint256 hash = tx.GetHash();
if (!txdb.ContainsTx(hash))
RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
}
}
if (!IsCoinBase())
{
uint256 hash = GetHash();
if (!txdb.ContainsTx(hash))
{
printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
}
}
}
void CWalletTx::RelayWalletTransaction()
{
CTxDB txdb("r");
RelayWalletTransaction(txdb);
}
void CWallet::ResendWalletTransactions()
{
// Do this infrequently and randomly to avoid giving away
// that these are our transactions.
static int64 nNextTime;
if (GetTime() < nNextTime)
return;
bool fFirst = (nNextTime == 0);
nNextTime = GetTime() + GetRand(30 * 60);
if (fFirst)
return;
// Only do it if there's been a new block since last time
static int64 nLastTime;
if (nTimeBestReceived < nLastTime)
return;
nLastTime = GetTime();
// Rebroadcast any of our txes that aren't in a block yet
printf("ResendWalletTransactions()\n");
CTxDB txdb("r");
CRITICAL_BLOCK(cs_mapWallet)
{
// Sort them in chronological order
multimap<unsigned int, CWalletTx*> mapSorted;
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{
CWalletTx& wtx = item.second;
// Don't rebroadcast until it's had plenty of time that
// it should have gotten in already by now.
if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
}
BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
{
CWalletTx& wtx = *item.second;
wtx.RelayWalletTransaction(txdb);
}
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Actions
//
int64 CWallet::GetBalance() const
{
int64 nStart = GetTimeMillis();
int64 nTotal = 0;
CRITICAL_BLOCK(cs_mapWallet)
{
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
continue;
nTotal += pcoin->GetAvailableCredit();
}
}
//printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
return nTotal;
}
bool CWallet::SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
{
setCoinsRet.clear();
nValueRet = 0;
// List of values less than target
pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
coinLowestLarger.first = INT64_MAX;
coinLowestLarger.second.first = NULL;
vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
int64 nTotalLower = 0;
CRITICAL_BLOCK(cs_mapWallet)
{
vector<const CWalletTx*> vCoins;
vCoins.reserve(mapWallet.size());
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
vCoins.push_back(&(*it).second);
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
BOOST_FOREACH(const CWalletTx* pcoin, vCoins)
{
if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
continue;
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
continue;
for (int i = 0; i < pcoin->vout.size(); i++)
{
if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]))
continue;
int64 n = pcoin->vout[i].nValue;
if (n <= 0)
continue;
pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i));
if (n == nTargetValue)
{
setCoinsRet.insert(coin.second);
nValueRet += coin.first;
return true;
}
else if (n < nTargetValue + CENT)
{
vValue.push_back(coin);
nTotalLower += n;
}
else if (n < coinLowestLarger.first)
{
coinLowestLarger = coin;
}
}
}
}
if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT)
{
for (int i = 0; i < vValue.size(); ++i)
{
setCoinsRet.insert(vValue[i].second);
nValueRet += vValue[i].first;
}
return true;
}
if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0))
{
if (coinLowestLarger.second.first == NULL)
return false;
setCoinsRet.insert(coinLowestLarger.second);
nValueRet += coinLowestLarger.first;
return true;
}
if (nTotalLower >= nTargetValue + CENT)
nTargetValue += CENT;
// Solve subset sum by stochastic approximation
sort(vValue.rbegin(), vValue.rend());
vector<char> vfIncluded;
vector<char> vfBest(vValue.size(), true);
int64 nBest = nTotalLower;
for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
{
vfIncluded.assign(vValue.size(), false);
int64 nTotal = 0;
bool fReachedTarget = false;
for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
{
for (int i = 0; i < vValue.size(); i++)
{
if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
{
nTotal += vValue[i].first;
vfIncluded[i] = true;
if (nTotal >= nTargetValue)
{
fReachedTarget = true;
if (nTotal < nBest)
{
nBest = nTotal;
vfBest = vfIncluded;
}
nTotal -= vValue[i].first;
vfIncluded[i] = false;
}
}
}
}
}
// If the next larger is still closer, return it
if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue)
{
setCoinsRet.insert(coinLowestLarger.second);
nValueRet += coinLowestLarger.first;
}
else {
for (int i = 0; i < vValue.size(); i++)
if (vfBest[i])
{
setCoinsRet.insert(vValue[i].second);
nValueRet += vValue[i].first;
}
//// debug print
printf("SelectCoins() best subset: ");
for (int i = 0; i < vValue.size(); i++)
if (vfBest[i])
printf("%s ", FormatMoney(vValue[i].first).c_str());
printf("total %s\n", FormatMoney(nBest).c_str());
}
return true;
}
bool CWallet::SelectCoins(int64 nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
{
return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet, nValueRet) ||
SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet, nValueRet) ||
SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet, nValueRet));
}
bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
{
int64 nValue = 0;
BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
{
if (nValue < 0)
return false;
nValue += s.second;
}
if (vecSend.empty() || nValue < 0)
return false;
wtxNew.pwallet = this;
CRITICAL_BLOCK(cs_main)
{
// txdb must be opened before the mapWallet lock
CTxDB txdb("r");
CRITICAL_BLOCK(cs_mapWallet)
{
nFeeRet = nTransactionFee;
loop
{
wtxNew.vin.clear();
wtxNew.vout.clear();
wtxNew.fFromMe = true;
int64 nTotalValue = nValue + nFeeRet;
double dPriority = 0;
// vouts to the payees
BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
wtxNew.vout.push_back(CTxOut(s.second, s.first));
// Choose coins to use
set<pair<const CWalletTx*,unsigned int> > setCoins;
int64 nValueIn = 0;
if (!SelectCoins(nTotalValue, setCoins, nValueIn))
return false;
BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
{
int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
}
// Fill a vout back to self with any change
int64 nChange = nValueIn - nTotalValue;
if (nChange >= CENT)
{
// Note: We use a new key here to keep it from being obvious which side is the change.
// The drawback is that by not reusing a previous key, the change may be lost if a
// backup is restored, if the backup doesn't have the new private key for the change.
// If we reused the old key, it would be possible to add code to look for and
// rediscover unknown transactions that were written with keys of ours to recover
// post-backup change.
// Reserve a new key pair from key pool
vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
assert(mapKeys.count(vchPubKey));
// Fill a vout to ourself, using same address type as the payment
CScript scriptChange;
if (vecSend[0].first.GetBitcoinAddressHash160() != 0)
scriptChange.SetBitcoinAddress(vchPubKey);
else
scriptChange << vchPubKey << OP_CHECKSIG;
// Insert change txn at random position:
vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
}
else
reservekey.ReturnKey();
// Fill vin
BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
// Sign
int nIn = 0;
BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
return false;
// Limit size
unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
return false;
dPriority /= nBytes;
// Check that enough fee is included
int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
bool fAllowFree = CTransaction::AllowFree(dPriority);
int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
if (nFeeRet < max(nPayFee, nMinFee))
{
nFeeRet = max(nPayFee, nMinFee);
continue;
}
// Fill vtxPrev by copying from previous transactions vtxPrev
wtxNew.AddSupportingTransactions(txdb);
wtxNew.fTimeReceivedIsTxTime = true;
break;
}
}
}
return true;
}
bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
{
vector< pair<CScript, int64> > vecSend;
vecSend.push_back(make_pair(scriptPubKey, nValue));
return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet);
}
// Call after CreateTransaction unless you want to abort
bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
{
CRITICAL_BLOCK(cs_main)
{
printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
CRITICAL_BLOCK(cs_mapWallet)
{
// This is only to keep the database open to defeat the auto-flush for the
// duration of this scope. This is the only place where this optimization
// maybe makes sense; please don't do it anywhere else.
CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
// Take key pair from key pool so it won't be used again
reservekey.KeepKey();
// Add tx to wallet, because if it has change it's also ours,
// otherwise just for transaction history.
AddToWallet(wtxNew);
// Mark old coins as spent
set<CWalletTx*> setCoins;
BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
{
CWalletTx &coin = mapWallet[txin.prevout.hash];
coin.pwallet = this;
coin.MarkSpent(txin.prevout.n);
coin.WriteToDisk();
vWalletUpdated.push_back(coin.GetHash());
}
if (fFileBacked)
delete pwalletdb;
}
// Track how many getdata requests our transaction gets
CRITICAL_BLOCK(cs_mapRequestCount)
mapRequestCount[wtxNew.GetHash()] = 0;
// Broadcast
if (!wtxNew.AcceptToMemoryPool())
{
// This must not fail. The transaction has already been signed and recorded.
printf("CommitTransaction() : Error: Transaction not valid");
return false;
}
wtxNew.RelayWalletTransaction();
}
MainFrameRepaint();
return true;
}
// requires cs_main lock
string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
{
CReserveKey reservekey(this);
int64 nFeeRequired;
if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
{
string strError;
if (nValue + nFeeRequired > GetBalance())
strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str());
else
strError = _("Error: Transaction creation failed ");
printf("SendMoney() : %s", strError.c_str());
return strError;
}
if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
return "ABORTED";
if (!CommitTransaction(wtxNew, reservekey))
return _("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
MainFrameRepaint();
return "";
}
// requires cs_main lock
string CWallet::SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
{
// Check amount
if (nValue <= 0)
return _("Invalid amount");
if (nValue + nTransactionFee > GetBalance())
return _("Insufficient funds");
// Parse bitcoin address
CScript scriptPubKey;
if (!scriptPubKey.SetBitcoinAddress(strAddress))
return _("Invalid bitcoin address");
return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
}
bool CWallet::LoadWallet(bool& fFirstRunRet)
{
if (!fFileBacked)
return false;
fFirstRunRet = false;
if (!CWalletDB(strWalletFile,"cr+").LoadWallet(this))
return false;
fFirstRunRet = vchDefaultKey.empty();
if (!mapKeys.count(vchDefaultKey))
{
// Create new default key
RandAddSeedPerfmon();
vchDefaultKey = GetKeyFromKeyPool();
if (!SetAddressBookName(PubKeyToAddress(vchDefaultKey), ""))
return false;
CWalletDB(strWalletFile).WriteDefaultKey(vchDefaultKey);
}
CreateThread(ThreadFlushWalletDB, &strWalletFile);
return true;
}
+
+bool CWallet::SetAddressBookName(const string& strAddress, const string& strName)
+{
+ mapAddressBook[strAddress] = strName;
+ if (!fFileBacked)
+ return false;
+ return CWalletDB(strWalletFile).WriteName(strAddress, strName);
+}
+
+bool CWallet::DelAddressBookName(const string& strAddress)
+{
+ mapAddressBook.erase(strAddress);
+ if (!fFileBacked)
+ return false;
+ return CWalletDB(strWalletFile).EraseName(strAddress);
+}
+
+
void CWallet::PrintWallet(const CBlock& block)
{
CRITICAL_BLOCK(cs_mapWallet)
{
if (mapWallet.count(block.vtx[0].GetHash()))
{
CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
}
}
printf("\n");
}
bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
{
CRITICAL_BLOCK(cs_mapWallet)
{
map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
if (mi != mapWallet.end())
{
wtx = (*mi).second;
return true;
}
}
return false;
}
bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
{
if (!pwallet->fFileBacked)
return false;
strWalletFileOut = pwallet->strWalletFile;
return true;
}
void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
{
nIndex = -1;
keypool.vchPubKey.clear();
CRITICAL_BLOCK(cs_main)
CRITICAL_BLOCK(cs_mapWallet)
CRITICAL_BLOCK(cs_setKeyPool)
{
CWalletDB walletdb(strWalletFile);
// Top up key pool
int64 nTargetSize = max(GetArg("-keypool", 100), (int64)0);
while (setKeyPool.size() < nTargetSize+1)
{
int64 nEnd = 1;
if (!setKeyPool.empty())
nEnd = *(--setKeyPool.end()) + 1;
if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
throw runtime_error("ReserveKeyFromKeyPool() : writing generated key failed");
setKeyPool.insert(nEnd);
printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size());
}
// Get the oldest key
assert(!setKeyPool.empty());
nIndex = *(setKeyPool.begin());
setKeyPool.erase(setKeyPool.begin());
if (!walletdb.ReadPool(nIndex, keypool))
throw runtime_error("ReserveKeyFromKeyPool() : read failed");
if (!mapKeys.count(keypool.vchPubKey))
throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
assert(!keypool.vchPubKey.empty());
printf("keypool reserve %"PRI64d"\n", nIndex);
}
}
void CWallet::KeepKey(int64 nIndex)
{
// Remove from key pool
if (fFileBacked)
{
CWalletDB walletdb(strWalletFile);
CRITICAL_BLOCK(cs_main)
{
walletdb.ErasePool(nIndex);
}
}
printf("keypool keep %"PRI64d"\n", nIndex);
}
void CWallet::ReturnKey(int64 nIndex)
{
// Return to key pool
CRITICAL_BLOCK(cs_setKeyPool)
setKeyPool.insert(nIndex);
printf("keypool return %"PRI64d"\n", nIndex);
}
vector<unsigned char> CWallet::GetKeyFromKeyPool()
{
int64 nIndex = 0;
CKeyPool keypool;
ReserveKeyFromKeyPool(nIndex, keypool);
KeepKey(nIndex);
return keypool.vchPubKey;
}
int64 CWallet::GetOldestKeyPoolTime()
{
int64 nIndex = 0;
CKeyPool keypool;
ReserveKeyFromKeyPool(nIndex, keypool);
ReturnKey(nIndex);
return keypool.nTime;
}
vector<unsigned char> CReserveKey::GetReservedKey()
{
if (nIndex == -1)
{
CKeyPool keypool;
pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
vchPubKey = keypool.vchPubKey;
}
assert(!vchPubKey.empty());
return vchPubKey;
}
void CReserveKey::KeepKey()
{
if (nIndex != -1)
pwallet->KeepKey(nIndex);
nIndex = -1;
vchPubKey.clear();
}
void CReserveKey::ReturnKey()
{
if (nIndex != -1)
pwallet->ReturnKey(nIndex);
nIndex = -1;
vchPubKey.clear();
}
diff --git a/src/wallet.h b/src/wallet.h
index b069d31ce..bf7d8cc51 100644
--- a/src/wallet.h
+++ b/src/wallet.h
@@ -1,614 +1,613 @@
// Copyright (c) 2009-2011 Satoshi Nakamoto & Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_WALLET_H
#define BITCOIN_WALLET_H
#include "bignum.h"
#include "key.h"
#include "script.h"
class CWalletTx;
class CReserveKey;
class CWalletDB;
class CWallet : public CKeyStore
{
private:
bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
public:
bool fFileBacked;
std::string strWalletFile;
std::set<int64> setKeyPool;
CCriticalSection cs_setKeyPool;
CWallet()
{
fFileBacked = false;
}
CWallet(std::string strWalletFileIn)
{
strWalletFile = strWalletFileIn;
fFileBacked = true;
}
mutable CCriticalSection cs_mapWallet;
std::map<uint256, CWalletTx> mapWallet;
std::vector<uint256> vWalletUpdated;
std::map<uint256, int> mapRequestCount;
mutable CCriticalSection cs_mapRequestCount;
std::map<std::string, std::string> mapAddressBook;
mutable CCriticalSection cs_mapAddressBook;
std::vector<unsigned char> vchDefaultKey;
bool AddKey(const CKey& key);
bool AddToWallet(const CWalletTx& wtxIn);
bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate = false);
bool EraseFromWallet(uint256 hash);
void WalletUpdateSpent(const CTransaction& prevout);
int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
void ReacceptWalletTransactions();
void ResendWalletTransactions();
int64 GetBalance() const;
bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
bool BroadcastTransaction(CWalletTx& wtxNew);
std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
std::string SendMoneyToBitcoinAddress(std::string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
void KeepKey(int64 nIndex);
void ReturnKey(int64 nIndex);
std::vector<unsigned char> GetKeyFromKeyPool();
int64 GetOldestKeyPoolTime();
bool IsMine(const CTxIn& txin) const;
int64 GetDebit(const CTxIn& txin) const;
bool IsMine(const CTxOut& txout) const
{
return ::IsMine(*this, txout.scriptPubKey);
}
int64 GetCredit(const CTxOut& txout) const
{
if (!MoneyRange(txout.nValue))
throw std::runtime_error("CWallet::GetCredit() : value out of range");
return (IsMine(txout) ? txout.nValue : 0);
}
bool IsChange(const CTxOut& txout) const
{
std::vector<unsigned char> vchPubKey;
if (ExtractPubKey(txout.scriptPubKey, this, vchPubKey))
CRITICAL_BLOCK(cs_mapAddressBook)
if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
return true;
return false;
}
int64 GetChange(const CTxOut& txout) const
{
if (!MoneyRange(txout.nValue))
throw std::runtime_error("CWallet::GetChange() : value out of range");
return (IsChange(txout) ? txout.nValue : 0);
}
bool IsMine(const CTransaction& tx) const
{
BOOST_FOREACH(const CTxOut& txout, tx.vout)
if (IsMine(txout))
return true;
return false;
}
bool IsFromMe(const CTransaction& tx) const
{
return (GetDebit(tx) > 0);
}
int64 GetDebit(const CTransaction& tx) const
{
int64 nDebit = 0;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
nDebit += GetDebit(txin);
if (!MoneyRange(nDebit))
throw std::runtime_error("CWallet::GetDebit() : value out of range");
}
return nDebit;
}
int64 GetCredit(const CTransaction& tx) const
{
int64 nCredit = 0;
BOOST_FOREACH(const CTxOut& txout, tx.vout)
{
nCredit += GetCredit(txout);
if (!MoneyRange(nCredit))
throw std::runtime_error("CWallet::GetCredit() : value out of range");
}
return nCredit;
}
int64 GetChange(const CTransaction& tx) const
{
int64 nChange = 0;
BOOST_FOREACH(const CTxOut& txout, tx.vout)
{
nChange += GetChange(txout);
if (!MoneyRange(nChange))
throw std::runtime_error("CWallet::GetChange() : value out of range");
}
return nChange;
}
void SetBestChain(const CBlockLocator& loc)
{
CWalletDB walletdb(strWalletFile);
walletdb.WriteBestBlock(loc);
}
bool LoadWallet(bool& fFirstRunRet);
// bool BackupWallet(const std::string& strDest);
- bool SetAddressBookName(const std::string& strAddress, const std::string& strName)
- {
- if (!fFileBacked)
- return false;
- return CWalletDB(strWalletFile).WriteName(strAddress, strName);
- }
+ // requires cs_mapAddressBook lock
+ bool SetAddressBookName(const std::string& strAddress, const std::string& strName);
+
+ // requires cs_mapAddressBook lock
+ bool DelAddressBookName(const std::string& strAddress);
void UpdatedTransaction(const uint256 &hashTx)
{
CRITICAL_BLOCK(cs_mapWallet)
vWalletUpdated.push_back(hashTx);
}
void PrintWallet(const CBlock& block);
void Inventory(const uint256 &hash)
{
CRITICAL_BLOCK(cs_mapRequestCount)
{
std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
if (mi != mapRequestCount.end())
(*mi).second++;
}
}
bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
};
class CReserveKey
{
protected:
CWallet* pwallet;
int64 nIndex;
std::vector<unsigned char> vchPubKey;
public:
CReserveKey(CWallet* pwalletIn)
{
nIndex = -1;
pwallet = pwalletIn;
}
~CReserveKey()
{
if (!fShutdown)
ReturnKey();
}
void ReturnKey();
std::vector<unsigned char> GetReservedKey();
void KeepKey();
};
//
// A transaction with a bunch of additional info that only the owner cares
// about. It includes any unrecorded transactions needed to link it back
// to the block chain.
//
class CWalletTx : public CMerkleTx
{
public:
const CWallet* pwallet;
std::vector<CMerkleTx> vtxPrev;
std::map<std::string, std::string> mapValue;
std::vector<std::pair<std::string, std::string> > vOrderForm;
unsigned int fTimeReceivedIsTxTime;
unsigned int nTimeReceived; // time received by this node
char fFromMe;
std::string strFromAccount;
std::vector<char> vfSpent;
// memory only
mutable char fDebitCached;
mutable char fCreditCached;
mutable char fAvailableCreditCached;
mutable char fChangeCached;
mutable int64 nDebitCached;
mutable int64 nCreditCached;
mutable int64 nAvailableCreditCached;
mutable int64 nChangeCached;
// memory only UI hints
mutable unsigned int nTimeDisplayed;
mutable int nLinesDisplayed;
mutable char fConfirmedDisplayed;
CWalletTx()
{
Init(NULL);
}
CWalletTx(const CWallet* pwalletIn)
{
Init(pwalletIn);
}
CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
{
Init(pwalletIn);
}
CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
{
Init(pwalletIn);
}
void Init(const CWallet* pwalletIn)
{
pwallet = pwalletIn;
vtxPrev.clear();
mapValue.clear();
vOrderForm.clear();
fTimeReceivedIsTxTime = false;
nTimeReceived = 0;
fFromMe = false;
strFromAccount.clear();
vfSpent.clear();
fDebitCached = false;
fCreditCached = false;
fAvailableCreditCached = false;
fChangeCached = false;
nDebitCached = 0;
nCreditCached = 0;
nAvailableCreditCached = 0;
nChangeCached = 0;
nTimeDisplayed = 0;
nLinesDisplayed = 0;
fConfirmedDisplayed = false;
}
IMPLEMENT_SERIALIZE
(
CWalletTx* pthis = const_cast<CWalletTx*>(this);
if (fRead)
pthis->Init(NULL);
char fSpent = false;
if (!fRead)
{
pthis->mapValue["fromaccount"] = pthis->strFromAccount;
std::string str;
BOOST_FOREACH(char f, vfSpent)
{
str += (f ? '1' : '0');
if (f)
fSpent = true;
}
pthis->mapValue["spent"] = str;
}
nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
READWRITE(vtxPrev);
READWRITE(mapValue);
READWRITE(vOrderForm);
READWRITE(fTimeReceivedIsTxTime);
READWRITE(nTimeReceived);
READWRITE(fFromMe);
READWRITE(fSpent);
if (fRead)
{
pthis->strFromAccount = pthis->mapValue["fromaccount"];
if (mapValue.count("spent"))
BOOST_FOREACH(char c, pthis->mapValue["spent"])
pthis->vfSpent.push_back(c != '0');
else
pthis->vfSpent.assign(vout.size(), fSpent);
}
pthis->mapValue.erase("fromaccount");
pthis->mapValue.erase("version");
pthis->mapValue.erase("spent");
)
// marks certain txout's as spent
// returns true if any update took place
bool UpdateSpent(const std::vector<char>& vfNewSpent)
{
bool fReturn = false;
for (int i=0; i < vfNewSpent.size(); i++)
{
if (i == vfSpent.size())
break;
if (vfNewSpent[i] && !vfSpent[i])
{
vfSpent[i] = true;
fReturn = true;
fAvailableCreditCached = false;
}
}
return fReturn;
}
void MarkDirty()
{
fCreditCached = false;
fAvailableCreditCached = false;
fDebitCached = false;
fChangeCached = false;
}
void MarkSpent(unsigned int nOut)
{
if (nOut >= vout.size())
throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
vfSpent.resize(vout.size());
if (!vfSpent[nOut])
{
vfSpent[nOut] = true;
fAvailableCreditCached = false;
}
}
bool IsSpent(unsigned int nOut) const
{
if (nOut >= vout.size())
throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
if (nOut >= vfSpent.size())
return false;
return (!!vfSpent[nOut]);
}
int64 GetDebit() const
{
if (vin.empty())
return 0;
if (fDebitCached)
return nDebitCached;
nDebitCached = pwallet->GetDebit(*this);
fDebitCached = true;
return nDebitCached;
}
int64 GetCredit(bool fUseCache=true) const
{
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
// GetBalance can assume transactions in mapWallet won't change
if (fUseCache && fCreditCached)
return nCreditCached;
nCreditCached = pwallet->GetCredit(*this);
fCreditCached = true;
return nCreditCached;
}
int64 GetAvailableCredit(bool fUseCache=true) const
{
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
if (fUseCache && fAvailableCreditCached)
return nAvailableCreditCached;
int64 nCredit = 0;
for (int i = 0; i < vout.size(); i++)
{
if (!IsSpent(i))
{
const CTxOut &txout = vout[i];
nCredit += pwallet->GetCredit(txout);
if (!MoneyRange(nCredit))
throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
}
}
nAvailableCreditCached = nCredit;
fAvailableCreditCached = true;
return nCredit;
}
int64 GetChange() const
{
if (fChangeCached)
return nChangeCached;
nChangeCached = pwallet->GetChange(*this);
fChangeCached = true;
return nChangeCached;
}
void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
int64& nSent, int64& nFee) const;
bool IsFromMe() const
{
return (GetDebit() > 0);
}
bool IsConfirmed() const
{
// Quick answer in most cases
if (!IsFinal())
return false;
if (GetDepthInMainChain() >= 1)
return true;
if (!IsFromMe()) // using wtx's cached debit
return false;
// If no confirmations but it's from us, we can still
// consider it confirmed if all dependencies are confirmed
std::map<uint256, const CMerkleTx*> mapPrev;
std::vector<const CMerkleTx*> vWorkQueue;
vWorkQueue.reserve(vtxPrev.size()+1);
vWorkQueue.push_back(this);
for (int i = 0; i < vWorkQueue.size(); i++)
{
const CMerkleTx* ptx = vWorkQueue[i];
if (!ptx->IsFinal())
return false;
if (ptx->GetDepthInMainChain() >= 1)
continue;
if (!pwallet->IsFromMe(*ptx))
return false;
if (mapPrev.empty())
BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
mapPrev[tx.GetHash()] = &tx;
BOOST_FOREACH(const CTxIn& txin, ptx->vin)
{
if (!mapPrev.count(txin.prevout.hash))
return false;
vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
}
}
return true;
}
bool WriteToDisk();
int64 GetTxTime() const;
int GetRequestCount() const;
void AddSupportingTransactions(CTxDB& txdb);
bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
bool AcceptWalletTransaction();
void RelayWalletTransaction(CTxDB& txdb);
void RelayWalletTransaction();
};
//
// Private key that includes an expiration date in case it never gets used.
//
class CWalletKey
{
public:
CPrivKey vchPrivKey;
int64 nTimeCreated;
int64 nTimeExpires;
std::string strComment;
//// todo: add something to note what created it (user, getnewaddress, change)
//// maybe should have a map<string, string> property map
CWalletKey(int64 nExpires=0)
{
nTimeCreated = (nExpires ? GetTime() : 0);
nTimeExpires = nExpires;
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vchPrivKey);
READWRITE(nTimeCreated);
READWRITE(nTimeExpires);
READWRITE(strComment);
)
};
//
// Account information.
// Stored in wallet with key "acc"+string account name
//
class CAccount
{
public:
std::vector<unsigned char> vchPubKey;
CAccount()
{
SetNull();
}
void SetNull()
{
vchPubKey.clear();
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vchPubKey);
)
};
//
// Internal transfers.
// Database key is acentry<account><counter>
//
class CAccountingEntry
{
public:
std::string strAccount;
int64 nCreditDebit;
int64 nTime;
std::string strOtherAccount;
std::string strComment;
CAccountingEntry()
{
SetNull();
}
void SetNull()
{
nCreditDebit = 0;
nTime = 0;
strAccount.clear();
strOtherAccount.clear();
strComment.clear();
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
// Note: strAccount is serialized as part of the key, not here.
READWRITE(nCreditDebit);
READWRITE(nTime);
READWRITE(strOtherAccount);
READWRITE(strComment);
)
};
bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
#endif

File Metadata

Mime Type
text/x-diff
Expires
Sun, Mar 2, 10:41 (1 d, 11 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
5187380
Default Alt Text
(222 KB)

Event Timeline