Skip to content

feat: add logarithmic block locators for getheaders and getblocks - #30

Merged
rustaceanrob merged 1 commit into
kernel-node:masterfrom
pzafonte:multi-peer-ibd-v2
Mar 24, 2026
Merged

rustaceanrob merged 1 commit into
kernel-node:masterfrom
pzafonte:multi-peer-ibd-v2

Conversation

@pzafonte

@pzafonte pzafonte commented Mar 5, 2026 •

Copy link
Copy Markdown
Collaborator

The single-hash locator requires the remote peer to scan from genesis if the local and remote chains have diverged beyond that one known block, producing unnecessarily large getheaders responses.

A logarithmic locator sends exponentially spaced hashes from the active chain tip, allowing the remote peer to binary-search for the fork point in O(log N) steps regardless of reorg depth.

Approaches that I'm referencing in the Bitcoin P2P protocol and used by Bitcoin Core, here:
Logarithmic locator algorithm - src/chain.cpp L26-43
Null stop_hash convention - PR #25454, Protocol docs

Comment thread src/peer.rs Resolved
Comment thread src/peer.rs Resolved
Comment thread src/peer.rs Resolved
Comment thread src/peer.rs Resolved
@rustaceanrob

rustaceanrob commented Mar 5, 2026 •

Copy link
Copy Markdown
Contributor

It appears you have an auto-formatter on. This is usually fine however we don't have a proper CI setup yet. Can we remove the formatting changes for now to make the commits more legible?

edit: Opened #34 to fix this

@rustaceanrob rustaceanrob mentioned this pull request Mar 5, 2026

@pzafonte pzafonte left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

  • Revert auto-formatter noise in peer.rs until proper CI can be set up
  • Remove inline rationale comment from build_block_locator
  • Pre-allocate locator vector with Vec::with_capacity(MAX_LOCATOR_HASHES)
  • Cap locator at 101 hashes, matching Bitcoin Core's MAX_LOCATOR_SZ

Comment thread src/peer.rs Resolved
Comment thread src/peer.rs Resolved
Comment thread src/bin/node.rs

fn setup_logging() {
let mut builder = env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"));
let mut builder =

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Your PR would be a little nicer if you didn't combine format refactors and new work. I guess you probably ran cargo fmt, but it would be better to make a fmt commit prior to this new work so this commit diff is smaller and more human readable.

Comment thread src/peer.rs

/// State Machine for setting up a connection and getting blocks from a peer
///
/// ```text

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ditto to above comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@pzafonte remove any auto-formatting in text editors. This is not a standard cargo fmt check and should be removed from the PR.

Comment thread src/peer.rs Resolved
@yancyribbens

Copy link
Copy Markdown
Contributor

This is the approach specified in the Bitcoin P2P protocol and used by Bitcoin Core.

Could you provide a specific entry/line number/spec you are basing this work on, either in the PR, or in the commit message? That would help reviewers follow along more closely.

Comment thread src/peer.rs Resolved
@pzafonte

pzafonte commented Mar 6, 2026

Copy link
Copy Markdown
Collaborator Author

This is the approach specified in the Bitcoin P2P protocol and used by Bitcoin Core.

Could you provide a specific entry/line number/spec you are basing this work on, either in the PR, or in the commit message? That would help reviewers follow along more closely.

Added in the body of the PR.

@rustaceanrob

Copy link
Copy Markdown
Contributor

Rebase this on master please

@yancyribbens

Copy link
Copy Markdown
Contributor

I wonder if it's possible to add some benchmarking to show now that the header locator is more efficient than before. That seems to be the primary goal of this PR after all if I understand correctly.

@yancyribbens

Copy link
Copy Markdown
Contributor

On second thought, this PR looks to reduce the size of the data set returned, not the time it takes?

@yancyribbens

Copy link
Copy Markdown
Contributor

Along those lines, have you actually tested this and been able to show the size is reduced from the previous locator?

@rustaceanrob

rustaceanrob commented Mar 7, 2026 •

Copy link
Copy Markdown
Contributor

The goal of this pull request is to allow the node to recover from a block reorganization when the node was shut down on a stale block. If the data request only include the stale block hash as a reference, the receiving node will be unable to respond to the request. Instead, we need to send a set of hashes that we are aware of, and the receiving node can respond to the hash that is in their chain of most work. Here is some documentation on this. If you are curious why an exponential backoff is used, I suggest creating a stack exchange question, as I am unsure why as well.

On that note, PR description is wrong. Nodes that receive a getdata for a block that is stale will not respond.

@yancyribbens

Copy link
Copy Markdown
Contributor

The goal of this pull request is to allow the node to recover from a block reorganization when the node was shut down on a stale block.

Thanks, that helps. This is something I would like to have seen better explained by the author. Otherwise, as a reviewer, it's hard to understand why this PR is being created unless they can clearly say what the problem is that is being addressed.

Is there actually an issue that spurred this? Which also begs the question, can the issue be reproduced so it can be shown that this change fixes it?

If you are curious why an exponential backoff is used, I suggest creating a stack exchange question, as I am unsure why as well.

The PR author put this in the commit message:

Replace the single-hash locator with a logarithmic block locator .. This lets the remote peer find the common fork point
efficiently even after a deep reorg, at the cost of a slightly larger
getheaders payload.

@pzafonte can you describe better what you mean by "efficiently" here. Is it something that could be measured by a benchmark or other mechanism?

@pzafonte
pzafonte force-pushed the multi-peer-ibd-v2 branch from cfe38d6 to 6f2dcfc Compare March 7, 2026 17:01
@rustaceanrob

Copy link
Copy Markdown
Contributor

Remove all the tests please. Majority of the attributes are tested in the underlying crate.

@rustaceanrob

Copy link
Copy Markdown
Contributor

After doing so, rebase this into a single commit. git rebase -i HEAD~5

@pzafonte
pzafonte force-pushed the multi-peer-ibd-v2 branch from 6f2dcfc to 7ec01d7 Compare March 7, 2026 19:12
@yancyribbens

Copy link
Copy Markdown
Contributor

@rustaceanrob i'm pretty sure we are talking to an LLM. His site is just a bunch of 404 links from https://pzafonte.dev/ and none of his profiles including Github go back further than 2025 - like he never existed until recently.

@pzafonte

pzafonte commented Mar 7, 2026 •

Copy link
Copy Markdown
Collaborator Author

Hey- I am not an LLM! I've worked as a Unix System Programmer (C/C++/Perl/Python) and Back End Developer (Go) over the course of my career. And now I'm doing Chaincode Labs BOSS Challenge where I picked up Rust. I am however new to the world of open source!

As I am coming in fresh on a lot of this particularly in the Bitcoin open source world, a lot of my previous experience overlaps so when I saw there was uncertainty about the logarithmic locator algorithm, I decided to do my research on the background of it's implementation, tried to apply my comp sci education, systems and network programming experience, etc etc. If there's something I'm not grasping or gaps please tell me, because I am genuinely trying to get a grasp on bitcoin open source and contribute.

@pzafonte
pzafonte force-pushed the multi-peer-ibd-v2 branch from 7ec01d7 to 50ef210 Compare March 8, 2026 03:28
@pzafonte

pzafonte commented Mar 8, 2026 •

Copy link
Copy Markdown
Collaborator Author

@yancyribbens if a bench mark is what you need, here is one

Of course all of this is contingent on peer quality!

Run this script
bench-ibd.sh

Against two log files like this.
./node-upstream --network signet --datadir ~/.kernel-node-upstream 2>&1 | tee sync-upstream.log
./node-locator --network signet --datadir ~/.kernel-node-locator 2>&1 | tee sync-locator.log

Let me know if what I'm measuring is correct...

Here's my output thus far...

============================================================
  IBD Benchmark Comparison
============================================================

[ sync-locator.log ]
  Log:                  sync-locator.log
  Node started:         2026-03-08T03:43:06Z
  Header sync done:     2026-03-08T03:43:26Z
N/A  (first block validated)
  Header sync duration: 20s  (getheaders round trips happen here)
  Block sync duration:  1165s  (getblocks + validation)
  Total elapsed:        1185s
  Blocks validated:     47851  (max height: 47880)
  Throughput:           40.3 blocks/sec

[ sync-upstream.log ]
  Log:                  sync-upstream.log
  Node started:         2026-03-08T03:41:50Z
  Header sync done:     2026-03-08T03:42:14Z
N/A  (first block validated)
  Header sync duration: 24s  (getheaders round trips happen here)
  Block sync duration:  1237s  (getblocks + validation)
  Total elapsed:        1261s
  Blocks validated:     27106  (max height: 27127)
  Throughput:           21.4 blocks/sec

------------------------------------------------------------
  Seconds from node start to reach checkpoint height
------------------------------------------------------------
  Height     sync-locator.log     sync-upstream.log   
  1000       44s                  67s                 
  5000       159s                 217s                
  10000      305s                 455s                
  25000      732s                 1168s               
  50000      not reached          not reached         
  100000     not reached          not reached         
  150000     not reached          not reached         
  200000     not reached          not reached         
============================================================

Comment thread src/peer.rs Resolved
@kernel-node kernel-node deleted a comment from pzafonte Mar 8, 2026
@rustaceanrob

Copy link
Copy Markdown
Contributor

Ran 50ef210 localy. Appears to do what is intended by the pull request. Outstanding comment(s) have to be addressed.

@rustaceanrob

rustaceanrob commented Mar 8, 2026 •

Copy link
Copy Markdown
Contributor

@pzafonte I will try to offer words of advice. As you have seen, developing open protocols requires a high level of adversarial thinking. That, and the project @yancyribbens and I have mutually in common, rust-bitcoin, is inundated with LLM generated pull requests. Oftentimes, these pull requests waste the time of honest reviewers, and have very little cost to the code generator. This is one of a handful of reasons rust-bitcoin will move off of github.

With that context, and the property that any critical bug can result in user loss of funds for many of the projects we work on, contributors tend to be very opposed to use of LLMs. I don't particularly care if code is generated by an LLM, human, or otherwise, as long as it is of high quality, concise, and well-motivated (none of which LLMs are very good at generating yet). What I do care about is reading walls of text that consume time I could otherwise spend elsewhere. When contributing to open source, it is essential to be precise and concise in your language. If a contributor asks for a reference, provide the reference with minimal context, they can read it. If something is otherwise abnormal about your patch, place rationale in the commit message. Finally, always, always, use your own language. Comments generated by LLMs in the PR thread are a guaranteed way to get your PR ignored or closed.

For instance:

So PR 30 is restoring Satoshi's original design! (I did not realize this at first!)

While it is possible you wrote this, the sentence reads like an LLM. 1. "PR 30" instead of "This PR" 2. "restoring Satoshi's original design!" there is no Satoshi here. This project is like 2 months old.

I will add a CONTRIBUTING.md to put this in writing.

@pzafonte
pzafonte force-pushed the multi-peer-ibd-v2 branch from 50ef210 to 247a102 Compare March 8, 2026 22:58
@pzafonte

pzafonte commented Mar 8, 2026 •

Copy link
Copy Markdown
Collaborator Author

@rustaceanrob I am grateful and appreciative of the advice. I picked an "experimental" project to because I felt it would be more accessible to make a contribution to. Especially, as I'm discovering, that the "developer habits" over the course of my career both independently and in corporate settings seem to run counter to open source. And I genuinely don't wish to be an extra burden on reviewers. And It is a space I want to work in and want/need to learn the ropes in.

This is something I would like to have seen better explained by the author. Otherwise, as a reviewer, it's hard to understand why this PR is being created

My apologies for the wall of text, I did try to be succinct in my PR, and my original rationale was simply that it follows Bitcoin Core's approach and O(log n) is more efficient than O(n). Though I felt like I needed to "build a case" because it seemed as though my explanation wasn't good enough, and to be honest I wasn't sure what constitutes a good explanation in this space. Again thank you for giving me advice, it gives me a better idea of how to approach things next time.

Comment thread src/peer.rs Resolved
Comment thread src/peer.rs Resolved
@pzafonte
pzafonte force-pushed the multi-peer-ibd-v2 branch from 247a102 to e3f7fa1 Compare March 9, 2026 12:30
Comment thread src/peer.rs Outdated
(
PeerStateMachine::AwaitingHeaders,
vec![create_getheaders_message(best_hash)],
vec![create_getheaders_message(vec![best_hash])],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why is the new function not used here?

@pzafonte pzafonte Mar 9, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I was and am working on a solution to this. I realized that the Rust wrapper for btck_chain_get_by_height in chain protects against accessing entries beyond the validated tip -chain.rs

I think we need to pass in the tip as a starting point and walks backwards through the block index using .prev() from BlockTreeEntry

locators = build_block_locators(chainman.best_entry())
send getheaders(locators)
locators = build_block_locators(chainman.active_chain().tip())
send getblocks(locators)

Function should be something like this:

function build_block_locators(tip: BlockTreeEntry) -> [BlockHash]:
    height = tip.height()
    locators = []
    entry = tip
    current_height = height
    step = 1

    loop:
        locators.append(entry.block_hash())

        if current_height == 0 or len(locators) >= MAX_LOCATOR_HASHES:
            break

        if len(locators) > 10:
            step *= 2

        target = max(0, current_height - step)

        while current_height > target:
            entry = entry.prev()  
            current_height -= 1

    return locators

Will finish implementing later and test the performance against my shell script.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Will finish implementing later and test the performance against my shell script.

Was this a script you composed or one generated by an LLM? When I was curious about showing the performance difference with your proposed changes, I had more in mind something like criterion. There's probably other parts of the codebase that would benefit from bench-marking as well. Actually, I'm interested in trying out divan, just haven't found the time.

@pzafonte pzafonte Mar 9, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

With the exception of regular expressions, I'm writing it myself, and reusing old design patterns I've used over the years. I'm not familiar with these, would you like me to try to set one of them up?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

would you like me to try to set one of them up?

Sure, if you think it would be useful. Benchmarks are a great way to see that changes are empirically better..

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

10-minute benchmark results from f044be9 Good improvement! Though, benchmark suite would be good given the variability.

============================================================
  IBD Benchmark Comparison
============================================================

[ sync-current.log ]
  Log:                  sync-current.log
  Node started:         2026-03-09T23:44:49Z
  Header sync done:     2026-03-09T23:45:12Z
N/A  (first block validated)
  Header sync duration: 23s  (getheaders round trips happen here)
  Block sync duration:  576s  (getblocks + validation)
  Total elapsed:        599s
  Blocks validated:     19567  (max height: 19566)
  Throughput:           32.6 blocks/sec

[ sync-prev.log ]
  Log:                  sync-prev.log
  Node started:         2026-03-09T23:34:49Z
  Header sync done:     2026-03-09T23:35:37Z
N/A  (first block validated)
  Header sync duration: 48s  (getheaders round trips happen here)
  Block sync duration:  549s  (getblocks + validation)
  Total elapsed:        597s
  Blocks validated:     15246  (max height: 15245)
  Throughput:           25.5 blocks/sec

------------------------------------------------------------
  Seconds from node start to reach checkpoint height
------------------------------------------------------------
  Height     sync-current.log     sync-prev.log       
  1000       62s                  127s                
  5000       175s                 291s                
  10000      326s                 417s                
  25000      not reached          not reached         
  50000      not reached          not reached         
  100000     not reached          not reached         
  150000     not reached          not reached         
  200000     not reached          not reached         
============================================================
============================================================
  IBD Benchmark Comparison
============================================================

[ sync-current.log ]
  Log:                  sync-current.log
  Node started:         2026-03-09T22:29:36Z
  Header sync done:     2026-03-09T22:29:40Z
N/A  (first block validated)
  Header sync duration: 4s  (getheaders round trips happen here)
  Block sync duration:  594s  (getblocks + validation)
  Total elapsed:        598s
  Blocks validated:     226133  (max height: 226132)
  Throughput:           378.1 blocks/sec

[ sync-prev.log ]
  Log:                  sync-prev.log
  Node started:         2026-03-09T22:29:40Z
  Header sync done:     2026-03-09T22:29:51Z
N/A  (first block validated)
  Header sync duration: 11s  (getheaders round trips happen here)
  Block sync duration:  588s  (getblocks + validation)
  Total elapsed:        599s
  Blocks validated:     48190  (max height: 48189)
  Throughput:           80.4 blocks/sec

------------------------------------------------------------
  Seconds from node start to reach checkpoint height
------------------------------------------------------------
  Height     sync-current.log     sync-prev.log       
  1000       5s                   20s                 
  5000       11s                  69s                 
  10000      20s                  149s                
  25000      43s                  342s                
  50000      89s                  not reached         
  100000     186s                 not reached         
  150000     316s                 not reached         
  200000     450s                 not reached         
============================================================

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I was looking at the micro-benchmarking solutions that @yancyribbens had mentioned, and those are good for the function level. The only high-level performance benchmark suite I can find seems to only exist for Bitcoin Core. Ideally we can look at both types of benchmarking to make a thorough analysis of tradeoffs. I took the scripts I wrote earlier, and decided to make something more robust, and node agnostic, hopefully useful for more projects in the Bitcoin developer community. And wanted to make you aware of it here: Node-Bench I'm not sure if my methodology is the best it can be but it's probably better than nothing.

I did the same comparison as before, 5-trial, randomized peers, 10-minute comparison.

f044be9 vs e3f7fa1 — 5-trial, 10-minute comparison (signet)

============================================================
  node-bench comparison
============================================================
                               f044be9 (latest)   e3f7fa1 (prev)     Δ
  Header sync (s)              24                 49                 -104.2%
  Block sync (s)               575                550                +4.3%
  Throughput (blk/s)           37.9               18.3               -51.7%
  Max height                   206,017            23,364             -88.7%
  Blocks validated             22,676             10,967             -51.6%

  Stddev (blk/s)               ±153.0             ±11.0

------------------------------------------------------------
  Checkpoint times (s from start)
------------------------------------------------------------
  Height    f044be9    e3f7fa1
  1000       51s        107s
  5000      147s        281s
  10000     146s        317s
  25000      45s        not reached
  50000      97s        not reached
  100000    224s        not reached
  150000    358s        not reached
  200000    534s        not reached
============================================================

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I was looking at the micro-benchmarking solutions that @yancyribbens had mentioned, and those are good for the function level

Yeah I think we'd need to add some fixture data, like a small number of sample blocks or something like that in order to use criterion. It's also useful to be able to benchmark an actual running node though too I think.

@yancyribbens

Copy link
Copy Markdown
Contributor

I'm curious though, why would we not just use more c bindings to re-use the same c code as in bitcoin-core? That's how the block validation is being done since it's consensus critical code and must behave the same as the reference implementation.

@pzafonte

pzafonte commented Mar 13, 2026 •

Copy link
Copy Markdown
Collaborator Author

I think it's more p2p sync logic than consensus critical. I also don’t think core's current kernel C API exposes the pieces we’d need to reuse core’s implementation directly (via libbitcoinkernel). It gives us enough to re-implement it the way libbitcoinkernel already gives us access to.

@rustaceanrob

Copy link
Copy Markdown
Contributor

I am confused why this is still being framed as an optimization and being reviewed as such. The headers are 80 bytes, which are minuscule compared to block size. As I said in a previous comment, the locators are used to recover from shutdown on a stale block. While it has a side-effect of optimization during reorganizations, if we expect the network is honest most of the time, these are rarely more than a single block and should have essentially no effect on sync speed.

@rustaceanrob

Copy link
Copy Markdown
Contributor

Please squash these two commits into a single one

@rustaceanrob

rustaceanrob commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor

I'm curious though, why would we not just use more c bindings to re-use the same c code as in bitcoin-core? That's how the block validation is being done since it's consensus critical code and must behave the same as the reference implementation.

All C bindings are generated from Bitcoin Core source code. There needs to be a strong motivation to introduce new methods to that API. That being said, I don't think it would be a bad idea to simply have a locators method on ChainstateManager. @pzafonte would you be interested and willing to make a pull request to Bitcoin Core to add such a method?

@sedited

sedited commented Mar 13, 2026

Copy link
Copy Markdown
Collaborator

I think adding support for locators is within scope of the library. Obviously cannot guarantee that other reviewers would agree with that, but it seems like one of Bitcoin Core's primitive data structures.

Implement build_block_locators using BlockTreeEntry traversal to produce
a standard 32 hash logarithmic locator for use in getheaders messages.
Traverses the block tree via BlockTreeEntry rather than raw block hashes.
@pzafonte
pzafonte force-pushed the multi-peer-ibd-v2 branch from f044be9 to 9796a05 Compare March 13, 2026 19:34
@pzafonte

pzafonte commented Mar 17, 2026 •

Copy link
Copy Markdown
Collaborator Author

bitcoin/bitcoin#34843

@pzafonte

Copy link
Copy Markdown
Collaborator Author

bitcoin/bitcoin#34885

@rustaceanrob

Copy link
Copy Markdown
Contributor

I checked this out and added additional logs. Appears to work as intended. I completed IBD with both fresh and partial chainstates.

ACK 9796a05

@rustaceanrob
rustaceanrob merged commit 8f62627 into kernel-node:master Mar 24, 2026
1 check passed
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.

4 participants