Skip to content

Commit ff6a7af

Browse files
luke-jrlaanwj
authored andcommitted
getblocktemplate: longpolling support
1 parent f0fc81a commit ff6a7af

File tree

6 files changed

+82
-1
lines changed

6 files changed

+82
-1
lines changed

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)