Repository navigation
feat: add logarithmic block locators for getheaders and getblocks - #30
Conversation
|
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 |
pzafonte
left a comment
There was a problem hiding this comment.
- 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
|
|
||
| fn setup_logging() { | ||
| let mut builder = env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")); | ||
| let mut builder = |
There was a problem hiding this comment.
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.
|
|
||
| /// State Machine for setting up a connection and getting blocks from a peer | ||
| /// | ||
| /// ```text |
There was a problem hiding this comment.
ditto to above comment
There was a problem hiding this comment.
@pzafonte remove any auto-formatting in text editors. This is not a standard cargo fmt check and should be removed from the PR.
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. |
|
Rebase this on |
|
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. |
|
On second thought, this PR looks to reduce the size of the data set returned, not the time it takes? |
|
Along those lines, have you actually tested this and been able to show the size is reduced from the previous locator? |
|
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 |
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?
The PR author put this in the commit message:
@pzafonte can you describe better what you mean by "efficiently" here. Is it something that could be measured by a benchmark or other mechanism? |
cfe38d6 to
6f2dcfc
Compare
|
Remove all the tests please. Majority of the attributes are tested in the underlying crate. |
|
After doing so, rebase this into a single commit. |
6f2dcfc to
7ec01d7
Compare
|
@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. |
|
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. |
7ec01d7 to
50ef210
Compare
|
@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 Against two log files like this. Let me know if what I'm measuring is correct... Here's my output thus far... |
|
Ran 50ef210 localy. Appears to do what is intended by the pull request. Outstanding comment(s) have to be addressed. |
|
@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, 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:
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 |
50ef210 to
247a102
Compare
|
@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.
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. |
247a102 to
e3f7fa1
Compare
| ( | ||
| PeerStateMachine::AwaitingHeaders, | ||
| vec![create_getheaders_message(best_hash)], | ||
| vec![create_getheaders_message(vec![best_hash])], |
There was a problem hiding this comment.
Why is the new function not used here?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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..
There was a problem hiding this comment.
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
============================================================
There was a problem hiding this comment.
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
============================================================
There was a problem hiding this comment.
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.
|
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. |
|
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. |
|
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. |
|
Please squash these two commits into a single one |
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 |
|
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.
f044be9 to
9796a05
Compare
|
I checked this out and added additional logs. Appears to work as intended. I completed IBD with both fresh and partial chainstates. ACK 9796a05 |
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
getheadersresponses.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.cppL26-43Null
stop_hashconvention - PR #25454, Protocol docs