Skip to content

Commit 3554df9

Browse files
committed
Merge pull request #4503
b45a6e8 Add test for getblocktemplate longpolling (Wladimir J. van der Laan) ff6a7af getblocktemplate: longpolling support (Luke Dashjr)
2 parents 08c6339 + b45a6e8 commit 3554df9

File tree

8 files changed

+179
-2
lines changed

8 files changed

+179
-2
lines changed

qa/rpc-tests/getblocktemplate.py

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
#!/usr/bin/env python
2+
# Copyright (c) 2014 The Bitcoin Core developers
3+
# Distributed under the MIT/X11 software license, see the accompanying
4+
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
5+
6+
# Exercise the listtransactions API
7+
8+
from test_framework import BitcoinTestFramework
9+
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
10+
from util import *
11+
12+
13+
def check_array_result(object_array, to_match, expected):
14+
"""
15+
Pass in array of JSON objects, a dictionary with key/value pairs
16+
to match against, and another dictionary with expected key/value
17+
pairs.
18+
"""
19+
num_matched = 0
20+
for item in object_array:
21+
all_match = True
22+
for key,value in to_match.items():
23+
if item[key] != value:
24+
all_match = False
25+
if not all_match:
26+
continue
27+
for key,value in expected.items():
28+
if item[key] != value:
29+
raise AssertionError("%s : expected %s=%s"%(str(item), str(key), str(value)))
30+
num_matched = num_matched+1
31+
if num_matched == 0:
32+
raise AssertionError("No objects matched %s"%(str(to_match)))
33+
34+
import threading
35+
36+
class LongpollThread(threading.Thread):
37+
def __init__(self, node):
38+
threading.Thread.__init__(self)
39+
# query current longpollid
40+
templat = node.getblocktemplate()
41+
self.longpollid = templat['longpollid']
42+
# create a new connection to the node, we can't use the same
43+
# connection from two threads
44+
self.node = AuthServiceProxy(node.url, timeout=600)
45+
46+
def run(self):
47+
self.node.getblocktemplate({'longpollid':self.longpollid})
48+
49+
class GetBlockTemplateTest(BitcoinTestFramework):
50+
'''
51+
Test longpolling with getblocktemplate.
52+
'''
53+
54+
def run_test(self, nodes):
55+
print "Warning: this test will take about 70 seconds in the best case. Be patient."
56+
nodes[0].setgenerate(True, 10)
57+
templat = nodes[0].getblocktemplate()
58+
longpollid = templat['longpollid']
59+
# longpollid should not change between successive invocations if nothing else happens
60+
templat2 = nodes[0].getblocktemplate()
61+
assert(templat2['longpollid'] == longpollid)
62+
63+
# Test 1: test that the longpolling wait if we do nothing
64+
thr = LongpollThread(nodes[0])
65+
thr.start()
66+
# check that thread still lives
67+
thr.join(5) # wait 5 seconds or until thread exits
68+
assert(thr.is_alive())
69+
70+
# Test 2: test that longpoll will terminate if another node generates a block
71+
nodes[1].setgenerate(True, 1) # generate a block on another node
72+
# check that thread will exit now that new transaction entered mempool
73+
thr.join(5) # wait 5 seconds or until thread exits
74+
assert(not thr.is_alive())
75+
76+
# Test 3: test that longpoll will terminate if we generate a block ourselves
77+
thr = LongpollThread(nodes[0])
78+
thr.start()
79+
nodes[0].setgenerate(True, 1) # generate a block on another node
80+
thr.join(5) # wait 5 seconds or until thread exits
81+
assert(not thr.is_alive())
82+
83+
# Test 4: test that introducing a new transaction into the mempool will terminate the longpoll
84+
thr = LongpollThread(nodes[0])
85+
thr.start()
86+
# generate a random transaction and submit it
87+
(txid, txhex, fee) = random_transaction(nodes, Decimal("1.1"), Decimal("0.0"), Decimal("0.001"), 20)
88+
# after one minute, every 10 seconds the mempool is probed, so in 80 seconds it should have returned
89+
thr.join(60 + 20)
90+
assert(not thr.is_alive())
91+
92+
if __name__ == '__main__':
93+
GetBlockTemplateTest().main()
94+

qa/rpc-tests/util.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,9 @@ def start_node(i, dir, extra_args=None, rpchost=None):
156156
["-rpcwait", "getblockcount"], stdout=devnull)
157157
devnull.close()
158158
url = "http://rt:rt@%s:%d" % (rpchost or '127.0.0.1', rpc_port(i))
159-
return AuthServiceProxy(url)
159+
proxy = AuthServiceProxy(url)
160+
proxy.url = url # store URL on proxy for info
161+
return proxy
160162

161163
def start_nodes(num_nodes, dir, extra_args=None, rpchost=None):
162164
"""

src/main.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ CCriticalSection cs_main;
4141
map<uint256, CBlockIndex*> mapBlockIndex;
4242
CChain chainActive;
4343
int64_t nTimeBestReceived = 0;
44+
CWaitableCriticalSection csBestBlock;
45+
CConditionVariable cvBlockChange;
4446
int nScriptCheckThreads = 0;
4547
bool fImporting = false;
4648
bool fReindex = false;
@@ -1944,11 +1946,14 @@ void static UpdateTip(CBlockIndex *pindexNew) {
19441946
// New best block
19451947
nTimeBestReceived = GetTime();
19461948
mempool.AddTransactionsUpdated(1);
1949+
19471950
LogPrintf("UpdateTip: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f\n",
19481951
chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
19491952
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
19501953
Checkpoints::GuessVerificationProgress(chainActive.Tip()));
19511954

1955+
cvBlockChange.notify_all();
1956+
19521957
// Check the version of the last 100 blocks to see if we need to upgrade:
19531958
if (!fIsInitialDownload)
19541959
{

src/main.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ extern uint64_t nLastBlockTx;
8787
extern uint64_t nLastBlockSize;
8888
extern const std::string strMessageMagic;
8989
extern int64_t nTimeBestReceived;
90+
extern CWaitableCriticalSection csBestBlock;
91+
extern CConditionVariable cvBlockChange;
9092
extern bool fImporting;
9193
extern bool fReindex;
9294
extern bool fBenchmark;

src/rpcmining.cpp

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,7 @@ Value getblocktemplate(const Array& params, bool fHelp)
324324
);
325325

326326
std::string strMode = "template";
327+
Value lpval = Value::null;
327328
if (params.size() > 0)
328329
{
329330
const Object& oparam = params[0].get_obj();
@@ -336,6 +337,7 @@ Value getblocktemplate(const Array& params, bool fHelp)
336337
}
337338
else
338339
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
340+
lpval = find_value(oparam, "longpollid");
339341
}
340342

341343
if (strMode != "template")
@@ -347,8 +349,63 @@ Value getblocktemplate(const Array& params, bool fHelp)
347349
if (IsInitialBlockDownload())
348350
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks...");
349351

350-
// Update block
351352
static unsigned int nTransactionsUpdatedLast;
353+
354+
if (lpval.type() != null_type)
355+
{
356+
// Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
357+
uint256 hashWatchedChain;
358+
boost::system_time checktxtime;
359+
unsigned int nTransactionsUpdatedLastLP;
360+
361+
if (lpval.type() == str_type)
362+
{
363+
// Format: <hashBestChain><nTransactionsUpdatedLast>
364+
std::string lpstr = lpval.get_str();
365+
366+
hashWatchedChain.SetHex(lpstr.substr(0, 64));
367+
nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
368+
}
369+
else
370+
{
371+
// NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
372+
hashWatchedChain = chainActive.Tip()->GetBlockHash();
373+
nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
374+
}
375+
376+
// Release the wallet and main lock while waiting
377+
#ifdef ENABLE_WALLET
378+
if(pwalletMain)
379+
LEAVE_CRITICAL_SECTION(pwalletMain->cs_wallet);
380+
#endif
381+
LEAVE_CRITICAL_SECTION(cs_main);
382+
{
383+
checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);
384+
385+
boost::unique_lock<boost::mutex> lock(csBestBlock);
386+
while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning())
387+
{
388+
if (!cvBlockChange.timed_wait(lock, checktxtime))
389+
{
390+
// Timeout: Check transactions for update
391+
if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
392+
break;
393+
checktxtime += boost::posix_time::seconds(10);
394+
}
395+
}
396+
}
397+
ENTER_CRITICAL_SECTION(cs_main);
398+
#ifdef ENABLE_WALLET
399+
if(pwalletMain)
400+
ENTER_CRITICAL_SECTION(pwalletMain->cs_wallet);
401+
#endif
402+
403+
if (!IsRPCRunning())
404+
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
405+
// TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
406+
}
407+
408+
// Update block
352409
static CBlockIndex* pindexPrev;
353410
static int64_t nStart;
354411
static CBlockTemplate* pblocktemplate;
@@ -436,6 +493,7 @@ Value getblocktemplate(const Array& params, bool fHelp)
436493
result.push_back(Pair("transactions", transactions));
437494
result.push_back(Pair("coinbaseaux", aux));
438495
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
496+
result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
439497
result.push_back(Pair("target", hashTarget.GetHex()));
440498
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
441499
result.push_back(Pair("mutable", aMutable));

src/rpcserver.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ using namespace std;
3232

3333
static std::string strRPCUserColonPass;
3434

35+
static bool fRPCRunning = false;
3536
// These are created by StartRPCThreads, destroyed in StopRPCThreads
3637
static asio::io_service* rpc_io_service = NULL;
3738
static map<string, boost::shared_ptr<deadline_timer> > deadlineTimers;
@@ -659,6 +660,7 @@ void StartRPCThreads()
659660
rpc_worker_group = new boost::thread_group();
660661
for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
661662
rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
663+
fRPCRunning = true;
662664
}
663665

664666
void StartDummyRPCThread()
@@ -671,12 +673,15 @@ void StartDummyRPCThread()
671673
rpc_dummy_work = new asio::io_service::work(*rpc_io_service);
672674
rpc_worker_group = new boost::thread_group();
673675
rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
676+
fRPCRunning = true;
674677
}
675678
}
676679

677680
void StopRPCThreads()
678681
{
679682
if (rpc_io_service == NULL) return;
683+
// Set this to false first, so that longpolling loops will exit when woken up
684+
fRPCRunning = false;
680685

681686
// First, cancel all timers and acceptors
682687
// This is not done automatically by ->stop(), and in some cases the destructor of
@@ -698,6 +703,7 @@ void StopRPCThreads()
698703
deadlineTimers.clear();
699704

700705
rpc_io_service->stop();
706+
cvBlockChange.notify_all();
701707
if (rpc_worker_group != NULL)
702708
rpc_worker_group->join_all();
703709
delete rpc_dummy_work; rpc_dummy_work = NULL;
@@ -706,6 +712,11 @@ void StopRPCThreads()
706712
delete rpc_io_service; rpc_io_service = NULL;
707713
}
708714

715+
bool IsRPCRunning()
716+
{
717+
return fRPCRunning;
718+
}
719+
709720
void RPCRunHandler(const boost::system::error_code& err, boost::function<void(void)> func)
710721
{
711722
if (!err)

src/rpcserver.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ void StartRPCThreads();
4040
void StartDummyRPCThread();
4141
/* Stop RPC threads */
4242
void StopRPCThreads();
43+
/* Query whether RPC is running */
44+
bool IsRPCRunning();
4345

4446
/*
4547
Type-check arguments; throws JSONRPCError if wrong type given. Does not check that

src/sync.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,9 @@ typedef AnnotatedMixin<boost::recursive_mutex> CCriticalSection;
8484
/** Wrapped boost mutex: supports waiting but not recursive locking */
8585
typedef AnnotatedMixin<boost::mutex> CWaitableCriticalSection;
8686

87+
/** Just a typedef for boost::condition_variable, can be wrapped later if desired */
88+
typedef boost::condition_variable CConditionVariable;
89+
8790
#ifdef DEBUG_LOCKORDER
8891
void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false);
8992
void LeaveCritical();

0 commit comments

Comments
 (0)