Skip to content

Conversation

@Sjors
Copy link
Collaborator

@Sjors Sjors commented Nov 7, 2025

This prevents repeating calls to getBlockHeader()

@Sjors
Copy link
Collaborator Author

Sjors commented Nov 7, 2025

@ryanofsky is there a way to make methods like getBlockHeader() cache their own result?

This prevents repeating calls to getBlockHeader()
@Sjors
Copy link
Collaborator Author

Sjors commented Nov 11, 2025

Rebased after #57.

};

while (!m_flag_interrupt_sv2) {
uint256 prev_hash;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @Sjors, I think there's an issue with the prev_hash variable in ThreadSv2ClientHandler.

Right now, prev_hash is declared at the top of the while loop but only gets assigned when block_template is null (inside that first if block). This works fine on the first iteration, but on subsequent iterations block_template won't be null anymore (since it gets updated at line 341), so the assignment never happens. This means the comparison if (new_prev_hash != prev_hash) ends up reading uninitialized memory.

I think the fix is pretty straightforward - just move prev_hash outside the loop and update it after each waitNext() call:

uint256 prev_hash;  // Move this before the while loop

while (!m_flag_interrupt_sv2) {
    if (!block_template) {
        // ... create template ...
        prev_hash = block_template->getBlockHeader().hashPrevBlock;
        m_block_template_cache.insert({template_id, std::make_pair(prev_hash, block_template)});
    }

    std::shared_ptr<BlockTemplate> tmpl = block_template->waitNext(options);
    if (tmpl) {
        block_template = tmpl;
        uint256 new_prev_hash{block_template->getBlockHeader().hashPrevBlock};
        
        if (new_prev_hash != prev_hash) {
            future_template = true;
            // ...
        }
        
        prev_hash = new_prev_hash;  // Add this line to update for next iteration
        m_block_template_cache.insert({m_template_id, std::make_pair(new_prev_hash, block_template)});
    }
}

This also has the nice side effect of removing that getBlockHeader() call that was happening every iteration in the original code (the old old_prev_hash line), so it's actually more optimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants