Skip to content

Commit e629a82

Browse files
committed
mining: add interrupt()
Both waitTipChanged() and createNewBlock() can take a long time to return. Add a way for clients to interrupt them. The new m_interrupt_mining is safely accessed with a lock on m_tip_block_mutex, but it has no guard annotation. A more thorough solution is discussed here: bitcoin#34184 (comment)
1 parent 0d4cf70 commit e629a82

File tree

6 files changed

+58
-17
lines changed

6 files changed

+58
-17
lines changed

src/interfaces/mining.h

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ class Mining
138138
* @param[in] timeout how long to wait for a new tip (default is forever)
139139
*
140140
* @retval BlockRef hash and height of the current chain tip after this call.
141-
* @retval std::nullopt if the node is shut down.
141+
* @retval std::nullopt if the node is shut down or interrupt() is called.
142142
*/
143143
virtual std::optional<BlockRef> waitTipChanged(uint256 current_tip, MillisecondsDouble timeout = MillisecondsDouble::max()) = 0;
144144

@@ -151,10 +151,15 @@ class Mining
151151
* tip to catch up. Recommended, except for regtest and
152152
* signets with only one miner.
153153
* @retval BlockTemplate a block template.
154-
* @retval std::nullptr if the node is shut down.
154+
* @retval std::nullptr if the node is shut down or interrupt() is called.
155155
*/
156156
virtual std::unique_ptr<BlockTemplate> createNewBlock(const node::BlockCreateOptions& options = {}, bool cooldown = false) = 0;
157157

158+
/**
159+
* Interrupts createNewBlock and waitTipChanged.
160+
*/
161+
virtual void interrupt() = 0;
162+
158163
/**
159164
* Checks if a given block is valid.
160165
*

src/ipc/capnp/mining.capnp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ interface Mining $Proxy.wrap("interfaces::Mining") {
1919
waitTipChanged @3 (context :Proxy.Context, currentTip: Data, timeout: Float64) -> (result: Common.BlockRef);
2020
createNewBlock @4 (context :Proxy.Context, options: BlockCreateOptions, cooldown: Bool) -> (result: BlockTemplate);
2121
checkBlock @5 (context :Proxy.Context, block: Data, options: BlockCheckOptions) -> (reason: Text, debug: Text, result: Bool);
22+
interrupt @6 () -> ();
2223
}
2324

2425
interface BlockTemplate $Proxy.wrap("interfaces::BlockTemplate") {

src/node/interfaces.cpp

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -964,7 +964,7 @@ class MinerImpl : public Mining
964964

965965
std::optional<BlockRef> waitTipChanged(uint256 current_tip, MillisecondsDouble timeout) override
966966
{
967-
return WaitTipChanged(chainman(), notifications(), current_tip, timeout);
967+
return WaitTipChanged(chainman(), notifications(), current_tip, timeout, m_interrupt_mining);
968968
}
969969

970970
std::unique_ptr<BlockTemplate> createNewBlock(const BlockCreateOptions& options, bool cooldown) override
@@ -982,18 +982,23 @@ class MinerImpl : public Mining
982982
// forever if no block was mined in the past day.
983983
while (chainman().IsInitialBlockDownload()) {
984984
maybe_tip = waitTipChanged(maybe_tip->hash, MillisecondsDouble{1000});
985-
if (!maybe_tip) return {};
985+
if (!maybe_tip || chainman().m_interrupt || WITH_LOCK(notifications().m_tip_block_mutex, return m_interrupt_mining)) return {};
986986
}
987987

988988
// Also wait during the final catch-up moments after IBD.
989-
if (!CooldownIfHeadersAhead(chainman(), notifications(), *maybe_tip)) return {};
989+
if (!CooldownIfHeadersAhead(chainman(), notifications(), *maybe_tip, m_interrupt_mining)) return {};
990990
}
991991

992992
BlockAssembler::Options assemble_options{options};
993993
ApplyArgsManOptions(*Assert(m_node.args), assemble_options);
994994
return std::make_unique<BlockTemplateImpl>(assemble_options, BlockAssembler{chainman().ActiveChainstate(), context()->mempool.get(), assemble_options}.CreateNewBlock(), m_node);
995995
}
996996

997+
void interrupt() override
998+
{
999+
InterruptWait(notifications(), m_interrupt_mining);
1000+
}
1001+
9971002
bool checkBlock(const CBlock& block, const node::BlockCheckOptions& options, std::string& reason, std::string& debug) override
9981003
{
9991004
LOCK(chainman().GetMutex());
@@ -1006,6 +1011,8 @@ class MinerImpl : public Mining
10061011
NodeContext* context() override { return &m_node; }
10071012
ChainstateManager& chainman() { return *Assert(m_node.chainman); }
10081013
KernelNotifications& notifications() { return *Assert(m_node.notifications); }
1014+
// Treat as if guarded by notifications().m_tip_block_mutex
1015+
bool m_interrupt_mining{false};
10091016
NodeContext& m_node;
10101017
};
10111018
} // namespace

src/node/miner.cpp

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -452,7 +452,7 @@ std::optional<BlockRef> GetTip(ChainstateManager& chainman)
452452
return BlockRef{tip->GetBlockHash(), tip->nHeight};
453453
}
454454

455-
bool CooldownIfHeadersAhead(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const BlockRef& last_tip)
455+
bool CooldownIfHeadersAhead(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const BlockRef& last_tip, bool& interrupt_mining)
456456
{
457457
uint256 last_tip_hash{last_tip.hash};
458458

@@ -465,9 +465,12 @@ bool CooldownIfHeadersAhead(ChainstateManager& chainman, KernelNotifications& ke
465465
WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
466466
kernel_notifications.m_tip_block_cv.wait_until(lock, cooldown_deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
467467
const auto tip_block = kernel_notifications.TipBlock();
468-
return chainman.m_interrupt || (tip_block && *tip_block != last_tip_hash);
468+
return chainman.m_interrupt || interrupt_mining || (tip_block && *tip_block != last_tip_hash);
469469
});
470-
if (chainman.m_interrupt) return false;
470+
if (chainman.m_interrupt || interrupt_mining) {
471+
interrupt_mining = false;
472+
return false;
473+
}
471474

472475
// If the tip changed during the wait, extend the deadline
473476
const auto tip_block = kernel_notifications.TipBlock();
@@ -484,7 +487,7 @@ bool CooldownIfHeadersAhead(ChainstateManager& chainman, KernelNotifications& ke
484487
return true;
485488
}
486489

487-
std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout)
490+
std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout, bool& interrupt)
488491
{
489492
Assume(timeout >= 0ms); // No internal callers should use a negative timeout
490493
if (timeout < 0ms) timeout = 0ms;
@@ -497,16 +500,22 @@ std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifi
497500
// always returns valid tip information when possible and only
498501
// returns null when shutting down, not when timing out.
499502
kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
500-
return kernel_notifications.TipBlock() || chainman.m_interrupt;
503+
return kernel_notifications.TipBlock() || chainman.m_interrupt || interrupt;
501504
});
502-
if (chainman.m_interrupt) return {};
505+
if (chainman.m_interrupt || interrupt) {
506+
interrupt = false;
507+
return {};
508+
}
503509
// At this point TipBlock is set, so continue to wait until it is
504510
// different then `current_tip` provided by caller.
505511
kernel_notifications.m_tip_block_cv.wait_until(lock, deadline, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
506-
return Assume(kernel_notifications.TipBlock()) != current_tip || chainman.m_interrupt;
512+
return Assume(kernel_notifications.TipBlock()) != current_tip || chainman.m_interrupt || interrupt;
507513
});
514+
if (chainman.m_interrupt || interrupt) {
515+
interrupt = false;
516+
return {};
517+
}
508518
}
509-
if (chainman.m_interrupt) return {};
510519

511520
// Must release m_tip_block_mutex before getTip() locks cs_main, to
512521
// avoid deadlocks.

src/node/miner.h

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ void ApplyArgsManOptions(const ArgsManager& gArgs, BlockAssembler::Options& opti
142142
void AddMerkleRootAndCoinbase(CBlock& block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce);
143143

144144

145-
/* Interrupt the current wait for the next block template. */
145+
/* Interrupt a blocking call. */
146146
void InterruptWait(KernelNotifications& kernel_notifications, bool& interrupt_wait);
147147
/**
148148
* Return a new block template when fees rise to a certain threshold or after a
@@ -160,8 +160,10 @@ std::unique_ptr<CBlockTemplate> WaitAndCreateNewBlock(ChainstateManager& chainma
160160
std::optional<BlockRef> GetTip(ChainstateManager& chainman);
161161

162162
/* Waits for the connected tip to change until timeout has elapsed. During node initialization, this will wait until the tip is connected (regardless of `timeout`).
163-
* Returns the current tip, or nullopt if the node is shutting down. */
164-
std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout);
163+
* Returns the current tip, or nullopt if the node is shutting down or interrupt()
164+
* is called.
165+
*/
166+
std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout, bool& interrupt);
165167

166168
/**
167169
* Wait while the best known header extends the current chain tip AND at least
@@ -178,10 +180,11 @@ std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifi
178180
* once per connected client. Subsequent templates are provided by waitNext().
179181
*
180182
* @param last_tip tip at the start of the cooldown window.
183+
* @param interrupt_mining set to true to interrupt the cooldown.
181184
*
182185
* @returns false if interrupted.
183186
*/
184-
bool CooldownIfHeadersAhead(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const BlockRef& last_tip);
187+
bool CooldownIfHeadersAhead(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const BlockRef& last_tip, bool& interrupt_mining);
185188
} // namespace node
186189

187190
#endif // BITCOIN_NODE_MINER_H

test/functional/interface_ipc_mining.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,14 @@ async def async_routine():
151151
assert_equal(oldblockref.hash, newblockref.hash)
152152
assert_equal(oldblockref.height, newblockref.height)
153153

154+
self.log.debug("interrupt() should abort waitTipChanged()")
155+
async def wait_for_tip():
156+
long_timeout = 60000.0 # 1 minute
157+
result = (await mining.waitTipChanged(ctx, newblockref.hash, long_timeout)).result
158+
# Unlike a timeout, interrupt() returns an empty BlockRef.
159+
assert_equal(len(result.hash), 0)
160+
await wait_and_do(wait_for_tip(), mining.interrupt())
161+
154162
asyncio.run(capnp.run(async_routine()))
155163

156164
def run_block_template_test(self):
@@ -177,6 +185,14 @@ async def async_routine():
177185
# spurious failures.
178186
assert_greater_than_or_equal(time.time() - start, 0.9)
179187

188+
self.log.debug("interrupt() should abort createNewBlock() during cooldown")
189+
async def create_block():
190+
result = await mining.createNewBlock(ctx, self.default_block_create_options, cooldown=True)
191+
# interrupt() causes createNewBlock to return nullptr
192+
assert_equal(result._has("result"), False)
193+
194+
await wait_and_do(create_block(), mining.interrupt())
195+
180196
header_only_peer.peer_disconnect()
181197
self.connect_nodes(0, 1)
182198
self.sync_all()

0 commit comments

Comments
 (0)