diff options
-rw-r--r-- | contrib/debian/manpages/bitcoin.conf.5 | 2 | ||||
-rwxr-xr-x | contrib/macdeploy/macdeployqtplus | 3 | ||||
-rwxr-xr-x | qa/rpc-tests/getblocktemplate.py | 94 | ||||
-rwxr-xr-x | qa/rpc-tests/keypool.py | 132 | ||||
-rw-r--r-- | qa/rpc-tests/util.py | 4 | ||||
-rw-r--r-- | src/init.cpp | 4 | ||||
-rw-r--r-- | src/leveldbwrapper.cpp | 5 | ||||
-rw-r--r-- | src/main.cpp | 5 | ||||
-rw-r--r-- | src/main.h | 2 | ||||
-rw-r--r-- | src/miner.cpp | 3 | ||||
-rw-r--r-- | src/qt/bitcoingui.cpp | 6 | ||||
-rw-r--r-- | src/rpcblockchain.cpp | 4 | ||||
-rw-r--r-- | src/rpcmining.cpp | 60 | ||||
-rw-r--r-- | src/rpcserver.cpp | 49 | ||||
-rw-r--r-- | src/rpcserver.h | 2 | ||||
-rw-r--r-- | src/rpcwallet.cpp | 2 | ||||
-rw-r--r-- | src/sync.h | 3 | ||||
-rw-r--r-- | src/wallet.cpp | 12 |
18 files changed, 353 insertions, 39 deletions
diff --git a/contrib/debian/manpages/bitcoin.conf.5 b/contrib/debian/manpages/bitcoin.conf.5 index 7438b4b66a..8a0078d5d5 100644 --- a/contrib/debian/manpages/bitcoin.conf.5 +++ b/contrib/debian/manpages/bitcoin.conf.5 @@ -2,7 +2,7 @@ .SH NAME bitcoin.conf \- bitcoin configuration file .SH SYNOPSIS -All command-line options (except for '\-datadir' and '\-conf') may be specified in a configuration file, and all configuration file options may also be specified on the command line. Command-line options override values set in the configuration file. +All command-line options (except for '\-conf') may be specified in a configuration file, and all configuration file options may also be specified on the command line. Command-line options override values set in the configuration file. .TP The configuration file is a list of 'setting=value' pairs, one per line, with optional comments starting with the '#' character. .TP diff --git a/contrib/macdeploy/macdeployqtplus b/contrib/macdeploy/macdeployqtplus index ce4169a410..fdad28018f 100755 --- a/contrib/macdeploy/macdeployqtplus +++ b/contrib/macdeploy/macdeployqtplus @@ -211,6 +211,7 @@ def getFrameworks(binaryPath, verbose): libraries = [] for line in otoolLines: + line = line.replace("@loader_path", os.path.dirname(binaryPath)) info = FrameworkInfo.fromOtoolLibraryLine(line.strip()) if info is not None: if verbose >= 3: @@ -307,7 +308,7 @@ def deployFrameworks(frameworks, bundlePath, binaryPath, strip, verbose, deploym if deploymentInfo.qtPath is None and framework.isQtFramework(): deploymentInfo.detectQtPath(framework.frameworkDirectory) - if framework.installName.startswith("@executable_path"): + if framework.installName.startswith("@executable_path") or framework.installName.startswith(bundlePath): if verbose >= 2: print framework.frameworkName, "already deployed, skipping." continue diff --git a/qa/rpc-tests/getblocktemplate.py b/qa/rpc-tests/getblocktemplate.py new file mode 100755 index 0000000000..8d97719ec3 --- /dev/null +++ b/qa/rpc-tests/getblocktemplate.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python +# Copyright (c) 2014 The Bitcoin Core developers +# Distributed under the MIT/X11 software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. + +# Exercise the listtransactions API + +from test_framework import BitcoinTestFramework +from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException +from util import * + + +def check_array_result(object_array, to_match, expected): + """ + Pass in array of JSON objects, a dictionary with key/value pairs + to match against, and another dictionary with expected key/value + pairs. + """ + num_matched = 0 + for item in object_array: + all_match = True + for key,value in to_match.items(): + if item[key] != value: + all_match = False + if not all_match: + continue + for key,value in expected.items(): + if item[key] != value: + raise AssertionError("%s : expected %s=%s"%(str(item), str(key), str(value))) + num_matched = num_matched+1 + if num_matched == 0: + raise AssertionError("No objects matched %s"%(str(to_match))) + +import threading + +class LongpollThread(threading.Thread): + def __init__(self, node): + threading.Thread.__init__(self) + # query current longpollid + templat = node.getblocktemplate() + self.longpollid = templat['longpollid'] + # create a new connection to the node, we can't use the same + # connection from two threads + self.node = AuthServiceProxy(node.url, timeout=600) + + def run(self): + self.node.getblocktemplate({'longpollid':self.longpollid}) + +class GetBlockTemplateTest(BitcoinTestFramework): + ''' + Test longpolling with getblocktemplate. + ''' + + def run_test(self, nodes): + print "Warning: this test will take about 70 seconds in the best case. Be patient." + nodes[0].setgenerate(True, 10) + templat = nodes[0].getblocktemplate() + longpollid = templat['longpollid'] + # longpollid should not change between successive invocations if nothing else happens + templat2 = nodes[0].getblocktemplate() + assert(templat2['longpollid'] == longpollid) + + # Test 1: test that the longpolling wait if we do nothing + thr = LongpollThread(nodes[0]) + thr.start() + # check that thread still lives + thr.join(5) # wait 5 seconds or until thread exits + assert(thr.is_alive()) + + # Test 2: test that longpoll will terminate if another node generates a block + nodes[1].setgenerate(True, 1) # generate a block on another node + # check that thread will exit now that new transaction entered mempool + thr.join(5) # wait 5 seconds or until thread exits + assert(not thr.is_alive()) + + # Test 3: test that longpoll will terminate if we generate a block ourselves + thr = LongpollThread(nodes[0]) + thr.start() + nodes[0].setgenerate(True, 1) # generate a block on another node + thr.join(5) # wait 5 seconds or until thread exits + assert(not thr.is_alive()) + + # Test 4: test that introducing a new transaction into the mempool will terminate the longpoll + thr = LongpollThread(nodes[0]) + thr.start() + # generate a random transaction and submit it + (txid, txhex, fee) = random_transaction(nodes, Decimal("1.1"), Decimal("0.0"), Decimal("0.001"), 20) + # after one minute, every 10 seconds the mempool is probed, so in 80 seconds it should have returned + thr.join(60 + 20) + assert(not thr.is_alive()) + +if __name__ == '__main__': + GetBlockTemplateTest().main() + diff --git a/qa/rpc-tests/keypool.py b/qa/rpc-tests/keypool.py new file mode 100755 index 0000000000..86ad20de52 --- /dev/null +++ b/qa/rpc-tests/keypool.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python +# Copyright (c) 2014 The Bitcoin Core developers +# Distributed under the MIT/X11 software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. + +# Exercise the wallet keypool, and interaction with wallet encryption/locking + +# Add python-bitcoinrpc to module search path: +import os +import sys +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "python-bitcoinrpc")) + +import json +import shutil +import subprocess +import tempfile +import traceback + +from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException +from util import * + + +def check_array_result(object_array, to_match, expected): + """ + Pass in array of JSON objects, a dictionary with key/value pairs + to match against, and another dictionary with expected key/value + pairs. + """ + num_matched = 0 + for item in object_array: + all_match = True + for key,value in to_match.items(): + if item[key] != value: + all_match = False + if not all_match: + continue + for key,value in expected.items(): + if item[key] != value: + raise AssertionError("%s : expected %s=%s"%(str(item), str(key), str(value))) + num_matched = num_matched+1 + if num_matched == 0: + raise AssertionError("No objects matched %s"%(str(to_match))) + +def run_test(nodes, tmpdir): + # Encrypt wallet and wait to terminate + nodes[0].encryptwallet('test') + bitcoind_processes[0].wait() + # Restart node 0 + nodes[0] = start_node(0, tmpdir) + # Keep creating keys + addr = nodes[0].getnewaddress() + try: + addr = nodes[0].getnewaddress() + raise AssertionError('Keypool should be exhausted after one address') + except JSONRPCException,e: + assert(e.error['code']==-12) + + # put three new keys in the keypool + nodes[0].walletpassphrase('test', 12000) + nodes[0].keypoolrefill(3) + nodes[0].walletlock() + + # drain the keys + addr = set() + addr.add(nodes[0].getrawchangeaddress()) + addr.add(nodes[0].getrawchangeaddress()) + addr.add(nodes[0].getrawchangeaddress()) + addr.add(nodes[0].getrawchangeaddress()) + # assert that four unique addresses were returned + assert(len(addr) == 4) + # the next one should fail + try: + addr = nodes[0].getrawchangeaddress() + raise AssertionError('Keypool should be exhausted after three addresses') + except JSONRPCException,e: + assert(e.error['code']==-12) + + +def main(): + import optparse + + parser = optparse.OptionParser(usage="%prog [options]") + parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true", + help="Leave bitcoinds and test.* datadir on exit or error") + parser.add_option("--srcdir", dest="srcdir", default="../../src", + help="Source directory containing bitcoind/bitcoin-cli (default: %default%)") + parser.add_option("--tmpdir", dest="tmpdir", default=tempfile.mkdtemp(prefix="test"), + help="Root directory for datadirs") + (options, args) = parser.parse_args() + + os.environ['PATH'] = options.srcdir+":"+os.environ['PATH'] + + check_json_precision() + + success = False + nodes = [] + try: + print("Initializing test directory "+options.tmpdir) + if not os.path.isdir(options.tmpdir): + os.makedirs(options.tmpdir) + initialize_chain(options.tmpdir) + + nodes = start_nodes(1, options.tmpdir) + + run_test(nodes, options.tmpdir) + + success = True + + except AssertionError as e: + print("Assertion failed: "+e.message) + except JSONRPCException as e: + print("JSONRPC error: "+e.error['message']) + traceback.print_tb(sys.exc_info()[2]) + except Exception as e: + print("Unexpected exception caught during testing: "+str(sys.exc_info()[0])) + traceback.print_tb(sys.exc_info()[2]) + + if not options.nocleanup: + print("Cleaning up") + stop_nodes(nodes) + wait_bitcoinds() + shutil.rmtree(options.tmpdir) + + if success: + print("Tests successful") + sys.exit(0) + else: + print("Failed") + sys.exit(1) + +if __name__ == '__main__': + main() diff --git a/qa/rpc-tests/util.py b/qa/rpc-tests/util.py index 0a7f26ffcd..fc7ae85776 100644 --- a/qa/rpc-tests/util.py +++ b/qa/rpc-tests/util.py @@ -156,7 +156,9 @@ def start_node(i, dir, extra_args=None, rpchost=None): ["-rpcwait", "getblockcount"], stdout=devnull) devnull.close() url = "http://rt:rt@%s:%d" % (rpchost or '127.0.0.1', rpc_port(i)) - return AuthServiceProxy(url) + proxy = AuthServiceProxy(url) + proxy.url = url # store URL on proxy for info + return proxy def start_nodes(num_nodes, dir, extra_args=None, rpchost=None): """ diff --git a/src/init.cpp b/src/init.cpp index 492070cbd9..9daad6ac89 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -219,7 +219,6 @@ std::string HelpMessage(HelpMessageMode mode) } strUsage += " -datadir=<dir> " + _("Specify data directory") + "\n"; strUsage += " -dbcache=<n> " + strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache) + "\n"; - strUsage += " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n"; strUsage += " -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + " " + _("on startup") + "\n"; strUsage += " -maxorphanblocks=<n> " + strprintf(_("Keep at most <n> unconnectable blocks in memory (default: %u)"), DEFAULT_MAX_ORPHAN_BLOCKS) + "\n"; strUsage += " -par=<n> " + strprintf(_("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"), -(int)boost::thread::hardware_concurrency(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS) + "\n"; @@ -260,6 +259,7 @@ std::string HelpMessage(HelpMessageMode mode) #ifdef ENABLE_WALLET strUsage += "\n" + _("Wallet options:") + "\n"; strUsage += " -disablewallet " + _("Do not load the wallet and disable wallet RPC calls") + "\n"; + strUsage += " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n"; if (GetBoolArg("-help-debug", false)) strUsage += " -mintxfee=<amt> " + strprintf(_("Fees (in BTC/Kb) smaller than this are considered zero fee for transaction creation (default: %s)"), FormatMoney(CWallet::minTxFee.GetFeePerK())) + "\n"; strUsage += " -paytxfee=<amt> " + strprintf(_("Fee (in BTC/kB) to add to transactions you send (default: %s)"), FormatMoney(payTxFee.GetFeePerK())) + "\n"; @@ -295,8 +295,10 @@ std::string HelpMessage(HelpMessageMode mode) if (mode == HMM_BITCOIN_QT) strUsage += ", qt"; strUsage += ".\n"; +#ifdef ENABLE_WALLET strUsage += " -gen " + _("Generate coins (default: 0)") + "\n"; strUsage += " -genproclimit=<n> " + _("Set the processor limit for when generation is on (-1 = unlimited, default: -1)") + "\n"; +#endif strUsage += " -help-debug " + _("Show all debugging options (usage: --help -help-debug)") + "\n"; strUsage += " -logips " + _("Include IP addresses in debug output (default: 0)") + "\n"; strUsage += " -logtimestamps " + _("Prepend debug output with timestamp (default: 1)") + "\n"; diff --git a/src/leveldbwrapper.cpp b/src/leveldbwrapper.cpp index 5b4a9c147b..9e849696a8 100644 --- a/src/leveldbwrapper.cpp +++ b/src/leveldbwrapper.cpp @@ -32,6 +32,11 @@ static leveldb::Options GetOptions(size_t nCacheSize) { options.filter_policy = leveldb::NewBloomFilterPolicy(10); options.compression = leveldb::kNoCompression; options.max_open_files = 64; + if (leveldb::kMajorVersion > 1 || (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) { + // LevelDB versions before 1.16 consider short writes to be corruption. Only trigger error + // on corruption in later versions. + options.paranoid_checks = true; + } return options; } diff --git a/src/main.cpp b/src/main.cpp index 8c119507e6..c5a3b284e8 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -41,6 +41,8 @@ CCriticalSection cs_main; map<uint256, CBlockIndex*> mapBlockIndex; CChain chainActive; int64_t nTimeBestReceived = 0; +CWaitableCriticalSection csBestBlock; +CConditionVariable cvBlockChange; int nScriptCheckThreads = 0; bool fImporting = false; bool fReindex = false; @@ -1945,11 +1947,14 @@ void static UpdateTip(CBlockIndex *pindexNew) { // New best block nTimeBestReceived = GetTime(); mempool.AddTransactionsUpdated(1); + LogPrintf("UpdateTip: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f\n", chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx, DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()), Checkpoints::GuessVerificationProgress(chainActive.Tip())); + cvBlockChange.notify_all(); + // Check the version of the last 100 blocks to see if we need to upgrade: if (!fIsInitialDownload) { diff --git a/src/main.h b/src/main.h index f6bac889be..a683412571 100644 --- a/src/main.h +++ b/src/main.h @@ -87,6 +87,8 @@ extern uint64_t nLastBlockTx; extern uint64_t nLastBlockSize; extern const std::string strMessageMagic; extern int64_t nTimeBestReceived; +extern CWaitableCriticalSection csBestBlock; +extern CConditionVariable cvBlockChange; extern bool fImporting; extern bool fReindex; extern bool fBenchmark; diff --git a/src/miner.cpp b/src/miner.cpp index 17918a1280..ec56c71192 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -467,7 +467,10 @@ void static BitcoinMiner(CWallet *pwallet) auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey)); if (!pblocktemplate.get()) + { + LogPrintf("Error in BitcoinMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n"); return; + } CBlock *pblock = &pblocktemplate->block; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); diff --git a/src/qt/bitcoingui.cpp b/src/qt/bitcoingui.cpp index 6b3aa2a2df..80d9fbff02 100644 --- a/src/qt/bitcoingui.cpp +++ b/src/qt/bitcoingui.cpp @@ -1012,7 +1012,7 @@ UnitDisplayStatusBarControl::UnitDisplayStatusBarControl():QLabel() setToolTip(tr("Unit to show amounts in. Click to select another unit.")); } -/** So that it responds to left-button clicks */ +/** So that it responds to button clicks */ void UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent *event) { onDisplayUnitsClicked(event->pos()); @@ -1029,10 +1029,6 @@ void UnitDisplayStatusBarControl::createContextMenu() menu->addAction(menuAction); } connect(menu,SIGNAL(triggered(QAction*)),this,SLOT(onMenuSelection(QAction*))); - - // what happens on right click. - setContextMenuPolicy(Qt::CustomContextMenu); - connect(this,SIGNAL(customContextMenuRequested(const QPoint&)),this,SLOT(onDisplayUnitsClicked(const QPoint&))); } /** Lets the control know about the Options Model (and its signals) */ diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index a67f266a13..253693e624 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -276,7 +276,9 @@ Value getblock(const Array& params, bool fHelp) CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; - ReadBlockFromDisk(block, pblockindex); + + if(!ReadBlockFromDisk(block, pblockindex)) + throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); if (!fVerbose) { diff --git a/src/rpcmining.cpp b/src/rpcmining.cpp index c7621dc137..6f72ea7404 100644 --- a/src/rpcmining.cpp +++ b/src/rpcmining.cpp @@ -324,6 +324,7 @@ Value getblocktemplate(const Array& params, bool fHelp) ); std::string strMode = "template"; + Value lpval = Value::null; if (params.size() > 0) { const Object& oparam = params[0].get_obj(); @@ -336,6 +337,7 @@ Value getblocktemplate(const Array& params, bool fHelp) } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); + lpval = find_value(oparam, "longpollid"); } if (strMode != "template") @@ -347,8 +349,63 @@ Value getblocktemplate(const Array& params, bool fHelp) if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks..."); - // Update block static unsigned int nTransactionsUpdatedLast; + + if (lpval.type() != null_type) + { + // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions + uint256 hashWatchedChain; + boost::system_time checktxtime; + unsigned int nTransactionsUpdatedLastLP; + + if (lpval.type() == str_type) + { + // Format: <hashBestChain><nTransactionsUpdatedLast> + std::string lpstr = lpval.get_str(); + + hashWatchedChain.SetHex(lpstr.substr(0, 64)); + nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64)); + } + else + { + // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier + hashWatchedChain = chainActive.Tip()->GetBlockHash(); + nTransactionsUpdatedLastLP = nTransactionsUpdatedLast; + } + + // Release the wallet and main lock while waiting +#ifdef ENABLE_WALLET + if(pwalletMain) + LEAVE_CRITICAL_SECTION(pwalletMain->cs_wallet); +#endif + LEAVE_CRITICAL_SECTION(cs_main); + { + checktxtime = boost::get_system_time() + boost::posix_time::minutes(1); + + boost::unique_lock<boost::mutex> lock(csBestBlock); + while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning()) + { + if (!cvBlockChange.timed_wait(lock, checktxtime)) + { + // Timeout: Check transactions for update + if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP) + break; + checktxtime += boost::posix_time::seconds(10); + } + } + } + ENTER_CRITICAL_SECTION(cs_main); +#ifdef ENABLE_WALLET + if(pwalletMain) + ENTER_CRITICAL_SECTION(pwalletMain->cs_wallet); +#endif + + if (!IsRPCRunning()) + throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down"); + // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners? + } + + // Update block static CBlockIndex* pindexPrev; static int64_t nStart; static CBlockTemplate* pblocktemplate; @@ -436,6 +493,7 @@ Value getblocktemplate(const Array& params, bool fHelp) result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue)); + result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast))); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1)); result.push_back(Pair("mutable", aMutable)); diff --git a/src/rpcserver.cpp b/src/rpcserver.cpp index 18fa075101..7d7e03d96b 100644 --- a/src/rpcserver.cpp +++ b/src/rpcserver.cpp @@ -32,6 +32,7 @@ using namespace std; static std::string strRPCUserColonPass; +static bool fRPCRunning = false; // These are created by StartRPCThreads, destroyed in StopRPCThreads static asio::io_service* rpc_io_service = NULL; static map<string, boost::shared_ptr<deadline_timer> > deadlineTimers; @@ -232,8 +233,8 @@ static const CRPCCommand vRPCCommands[] = { "getblockchaininfo", &getblockchaininfo, true, false, false }, { "getbestblockhash", &getbestblockhash, true, false, false }, { "getblockcount", &getblockcount, true, false, false }, - { "getblock", &getblock, false, false, false }, - { "getblockhash", &getblockhash, false, false, false }, + { "getblock", &getblock, true, false, false }, + { "getblockhash", &getblockhash, true, false, false }, { "getdifficulty", &getdifficulty, true, false, false }, { "getrawmempool", &getrawmempool, true, false, false }, { "gettxout", &gettxout, true, false, false }, @@ -245,32 +246,32 @@ static const CRPCCommand vRPCCommands[] = { "getmininginfo", &getmininginfo, true, false, false }, { "getnetworkhashps", &getnetworkhashps, true, false, false }, { "prioritisetransaction", &prioritisetransaction, true, false, false }, - { "submitblock", &submitblock, false, true, false }, + { "submitblock", &submitblock, true, true, false }, /* Raw transactions */ - { "createrawtransaction", &createrawtransaction, false, false, false }, - { "decoderawtransaction", &decoderawtransaction, false, false, false }, - { "decodescript", &decodescript, false, false, false }, - { "getrawtransaction", &getrawtransaction, false, false, false }, + { "createrawtransaction", &createrawtransaction, true, false, false }, + { "decoderawtransaction", &decoderawtransaction, true, false, false }, + { "decodescript", &decodescript, true, false, false }, + { "getrawtransaction", &getrawtransaction, true, false, false }, { "sendrawtransaction", &sendrawtransaction, false, false, false }, { "signrawtransaction", &signrawtransaction, false, false, false }, /* uses wallet if enabled */ /* Utility functions */ { "createmultisig", &createmultisig, true, true , false }, { "validateaddress", &validateaddress, true, false, false }, /* uses wallet if enabled */ - { "verifymessage", &verifymessage, false, false, false }, + { "verifymessage", &verifymessage, true, false, false }, { "estimatefee", &estimatefee, true, true, false }, { "estimatepriority", &estimatepriority, true, true, false }, #ifdef ENABLE_WALLET /* Wallet */ - { "addmultisigaddress", &addmultisigaddress, false, false, true }, + { "addmultisigaddress", &addmultisigaddress, true, false, true }, { "backupwallet", &backupwallet, true, false, true }, { "dumpprivkey", &dumpprivkey, true, false, true }, { "dumpwallet", &dumpwallet, true, false, true }, - { "encryptwallet", &encryptwallet, false, false, true }, + { "encryptwallet", &encryptwallet, true, false, true }, { "getaccountaddress", &getaccountaddress, true, false, true }, - { "getaccount", &getaccount, false, false, true }, + { "getaccount", &getaccount, true, false, true }, { "getaddressesbyaccount", &getaddressesbyaccount, true, false, true }, { "getbalance", &getbalance, false, false, true }, { "getnewaddress", &getnewaddress, true, false, true }, @@ -279,10 +280,10 @@ static const CRPCCommand vRPCCommands[] = { "getreceivedbyaddress", &getreceivedbyaddress, false, false, true }, { "gettransaction", &gettransaction, false, false, true }, { "getunconfirmedbalance", &getunconfirmedbalance, false, false, true }, - { "getwalletinfo", &getwalletinfo, true, false, true }, - { "importprivkey", &importprivkey, false, false, true }, - { "importwallet", &importwallet, false, false, true }, - { "importaddress", &importaddress, false, false, true }, + { "getwalletinfo", &getwalletinfo, false, false, true }, + { "importprivkey", &importprivkey, true, false, true }, + { "importwallet", &importwallet, true, false, true }, + { "importaddress", &importaddress, true, false, true }, { "keypoolrefill", &keypoolrefill, true, false, true }, { "listaccounts", &listaccounts, false, false, true }, { "listaddressgroupings", &listaddressgroupings, false, false, true }, @@ -292,16 +293,16 @@ static const CRPCCommand vRPCCommands[] = { "listsinceblock", &listsinceblock, false, false, true }, { "listtransactions", &listtransactions, false, false, true }, { "listunspent", &listunspent, false, false, true }, - { "lockunspent", &lockunspent, false, false, true }, + { "lockunspent", &lockunspent, true, false, true }, { "move", &movecmd, false, false, true }, { "sendfrom", &sendfrom, false, false, true }, { "sendmany", &sendmany, false, false, true }, { "sendtoaddress", &sendtoaddress, false, false, true }, { "setaccount", &setaccount, true, false, true }, - { "settxfee", &settxfee, false, false, true }, - { "signmessage", &signmessage, false, false, true }, + { "settxfee", &settxfee, true, false, true }, + { "signmessage", &signmessage, true, false, true }, { "walletlock", &walletlock, true, false, true }, - { "walletpassphrasechange", &walletpassphrasechange, false, false, true }, + { "walletpassphrasechange", &walletpassphrasechange, true, false, true }, { "walletpassphrase", &walletpassphrase, true, false, true }, /* Wallet-enabled mining */ @@ -659,6 +660,7 @@ void StartRPCThreads() rpc_worker_group = new boost::thread_group(); for (int i = 0; i < GetArg("-rpcthreads", 4); i++) rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service)); + fRPCRunning = true; } void StartDummyRPCThread() @@ -671,12 +673,15 @@ void StartDummyRPCThread() rpc_dummy_work = new asio::io_service::work(*rpc_io_service); rpc_worker_group = new boost::thread_group(); rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service)); + fRPCRunning = true; } } void StopRPCThreads() { if (rpc_io_service == NULL) return; + // Set this to false first, so that longpolling loops will exit when woken up + fRPCRunning = false; // First, cancel all timers and acceptors // This is not done automatically by ->stop(), and in some cases the destructor of @@ -698,6 +703,7 @@ void StopRPCThreads() deadlineTimers.clear(); rpc_io_service->stop(); + cvBlockChange.notify_all(); if (rpc_worker_group != NULL) rpc_worker_group->join_all(); delete rpc_dummy_work; rpc_dummy_work = NULL; @@ -706,6 +712,11 @@ void StopRPCThreads() delete rpc_io_service; rpc_io_service = NULL; } +bool IsRPCRunning() +{ + return fRPCRunning; +} + void RPCRunHandler(const boost::system::error_code& err, boost::function<void(void)> func) { if (!err) diff --git a/src/rpcserver.h b/src/rpcserver.h index e32eb975a1..31badadd6d 100644 --- a/src/rpcserver.h +++ b/src/rpcserver.h @@ -40,6 +40,8 @@ void StartRPCThreads(); void StartDummyRPCThread(); /* Stop RPC threads */ void StopRPCThreads(); +/* Query whether RPC is running */ +bool IsRPCRunning(); /* Type-check arguments; throws JSONRPCError if wrong type given. Does not check that diff --git a/src/rpcwallet.cpp b/src/rpcwallet.cpp index 1e46129065..e8c62fd37b 100644 --- a/src/rpcwallet.cpp +++ b/src/rpcwallet.cpp @@ -201,7 +201,7 @@ Value getrawchangeaddress(const Array& params, bool fHelp) CReserveKey reservekey(pwalletMain); CPubKey vchPubKey; if (!reservekey.GetReservedKey(vchPubKey)) - throw JSONRPCError(RPC_WALLET_ERROR, "Error: Unable to obtain key for change"); + throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); reservekey.KeepKey(); diff --git a/src/sync.h b/src/sync.h index 077ed59b89..cd319e0171 100644 --- a/src/sync.h +++ b/src/sync.h @@ -84,6 +84,9 @@ typedef AnnotatedMixin<boost::recursive_mutex> CCriticalSection; /** Wrapped boost mutex: supports waiting but not recursive locking */ typedef AnnotatedMixin<boost::mutex> CWaitableCriticalSection; +/** Just a typedef for boost::condition_variable, can be wrapped later if desired */ +typedef boost::condition_variable CConditionVariable; + #ifdef DEBUG_LOCKORDER void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false); void LeaveCritical(); diff --git a/src/wallet.cpp b/src/wallet.cpp index a54494f935..560cbc10b9 100644 --- a/src/wallet.cpp +++ b/src/wallet.cpp @@ -1075,7 +1075,7 @@ int64_t CWallet::GetWatchOnlyBalance() const { int64_t nTotal = 0; { - LOCK(cs_wallet); + LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; @@ -1091,7 +1091,7 @@ int64_t CWallet::GetUnconfirmedWatchOnlyBalance() const { int64_t nTotal = 0; { - LOCK(cs_wallet); + LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; @@ -1106,7 +1106,7 @@ int64_t CWallet::GetImmatureWatchOnlyBalance() const { int64_t nTotal = 0; { - LOCK(cs_wallet); + LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; @@ -2010,11 +2010,7 @@ bool CReserveKey::GetReservedKey(CPubKey& pubkey) if (nIndex != -1) vchPubKey = keypool.vchPubKey; else { - if (pwallet->vchDefaultKey.IsValid()) { - LogPrintf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!"); - vchPubKey = pwallet->vchDefaultKey; - } else - return false; + return false; } } assert(vchPubKey.IsValid()); |