Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. |
8af2757 to
befe560
Compare
befe560 to
cafcdc3
Compare
6ea0661 to
3dbae98
Compare
|
Could turn into draft while CI is red? |
3e9535e to
b985a41
Compare
6aa5f8d to
7d23abb
Compare
|
Concept ACK |
|
Approach ACK ; needs rebase if wanted for 32.0 I guess? |
|
Concept ACK |
7d23abb to
bf7d72a
Compare
|
Rebased. |
l0rinc
left a comment
There was a problem hiding this comment.
Concept ACK on calculating the parameters at startup from elapsed time since genesis, instead of predicting the release's lifetime.
I found the calculation difficult to review, and the lengthy derivations interspersed with the code made it harder to follow. I left a few simplification suggestions and a question about whether a small memory tradeoff could eliminate the searches, and whether the unbounded floating-point loop is safe (and whether we can eliminate it completely).
9f7bcfe to
9451c93
Compare
l0rinc
left a comment
There was a problem hiding this comment.
Only had time for a quick pass and left a few questions. I'll review more carefully later.
9451c93 to
02d1084
Compare
| }; | ||
|
|
||
| /** The peak per-peer memory a (period,bufsize) configuration needs. */ | ||
| auto memory_usage = [max_headers, minchainwork_headers](int64_t period, int64_t bufsize) noexcept -> int64_t { |
There was a problem hiding this comment.
nit: This lambda could be declared inside make_config to decrease cognitive complexity.
There was a problem hiding this comment.
I don't think that's very helpful.
02d1084 to
672e628
Compare
l0rinc
left a comment
There was a problem hiding this comment.
lightly tested ACK 672e628
Since my last review, the parameters are computed whenever a headers sync starts (addressing my clock-correction concern), and the test-vector generation script is now included.
I like the more compact code comments, and I'd still appreciate another pair of eyes to double-check the math.
The fixed test vectors could also be checked against the actual attack-rate formula, and the Python generator could move to contrib/testgen/, but neither suggestion is blocking for me.
Add ComputeHeadersSyncParams(), which finds (near-)optimal commitment period and redownload buffer size values for the headers sync DoS-protection mechanism, given the timespan since genesis and the number of headers in the minimum-chainwork chain, along with the internal ComputeHeadersSyncParamsInner() it is based on. The attack model treats headers as arriving one at a time, which slightly overestimates what an attacker can achieve (in reality headers arrive in batches that are only accepted in their entirety), but leads to a closed-form expression for the expected number of accepted forged headers. That expression can be inverted, which gives the buffer size needed for a given period directly, so only the period is searched for: by bisecting the legal range for the two adjacent periods which straddle the optimum of the problem's continuous relaxation, and comparing those two. If that optimum lies outside the legal range, the two periods nearest the corresponding end are compared instead. Also widen next_height in the presync header validation to int64_t, matching the m_current_height it is computed from. A presync chain is only bounded by 6 headers per second since genesis, so it can exceed INT_MAX headers, which the implicit truncation would turn into a negative height. The unit test checks 50 inputs against their exact optima, found by an exhaustive search over all periods. The script which samples such inputs and computes their optima is included with the test records.
Add two fuzz targets covering the headers sync parameter optimizer over a broad range of legal inputs, asserting that the resulting configuration is sane (and, implicitly, that the computation terminates without crashing or throwing): - headers_sync_params_inner exercises ComputeHeadersSyncParamsInner directly. minchainwork_headers is a block height and thus fits an int; max_headers must exceed twice that (which the caller guarantees by clamping) and is at most 6 headers/s over the longest timespan that std::chrono::seconds is guaranteed to represent; attack_headers is a positive rate, parametrized logarithmically over a wide range of magnitudes. - headers_sync_params exercises ComputeHeadersSyncParams over the portable range of std::chrono::seconds, and any int-height minchainwork_headers. Both targets check that the returned period is positive and no larger than the minimum-chainwork chain, and that the redownload buffer covers at least one commitment period whenever the acceptable attack rate is low enough to require any commitment verification at all (which it always is for the rates ComputeHeadersSyncParams uses).
672e628 to
0457cec
Compare
So far, the headers sync parameters are committed to the repository, as part of the chain parameters. This requires maintainers to occasionally recompute them, based on a prediction of how long the release is likely to be used. With the optimization algorithm now available in headerssync.cpp, it becomes possible to instead do this computation at runtime. This is less work, with fewer ways for maintainers and reviewers to get it wrong, and automatically adjusts based on clock time. The computation takes well under a microsecond, so it is simply redone whenever a headers sync is started. Doing it there, rather than once at startup, keeps the commitment period consistent with the bound that HeadersSyncState derives from the clock on how many commitments a peer may make us store: a node which starts up with a badly wrong clock and has it corrected before syncing would otherwise use a period sized for a much shorter chain than a peer can then feed it, inflating that bound (by a factor 50 for a clock which starts out before genesis). The fuzz targets which reach this code fix the clock around message processing, so the parameters they end up with do not vary with the fuzz input. As the chain parameters no longer hold them, HeadersSyncParams moves to headerssync.h, next to the code which computes and consumes it. Co-Authored-By: Lőrinc <[email protected]>
The headers sync parameters are now computed at runtime, so the tool that used to generate them for chainparams.cpp has no purpose anymore.
The test vectors compare against values obtained by a separate exhaustive search, so they detect changes in behavior, but not a mistake in that search. Establish instead, for each of them, that the configuration really is the one with the lowest memory usage, by evaluating the attack rate for every integer period, and for every integer bufsize up to the point where it becomes acceptable. Periods whose redownload buffer alone outweighs the best configuration found so far are ruled out by a bound rather than tried, which keeps the search over the recorded chain lengths affordable. The recorded bufsize is in addition held against the attack model itself, by averaging the accepted headers over the offset at which the attacker's first commitment check falls, instead of against the closed form that model is condensed into and inverted. Co-Authored-By: Lőrinc <[email protected]>
0457cec to
0316d0d
Compare
|
reACK 0316d0d |
| // commitment bits. Such a chain may be very long, by exploiting the timewarp bug to avoid | ||
| // ramping up difficulty. There is however an absolute limit on how long such a chain can be: 6 |
There was a problem hiding this comment.
nit: Decreasing the difficulty allows even faster hashing?
| // commitment bits. Such a chain may be very long, by exploiting the timewarp bug to avoid | |
| // ramping up difficulty. There is however an absolute limit on how long such a chain can be: 6 | |
| // commitment bits. Such a chain may be very long, by exploiting the timewarp bug to minimize | |
| // the difficulty. There is however an absolute limit on how long such a chain can be: 6 |
There was a problem hiding this comment.
If they fork off after genesis, indeed, but in this attack scenario (just wasting the victim's per-peer memory using the commitment bit data structure) I believe it is always better to start at genesis. Will address if I retouch.
| // the chain's age and minimum-chain-work header count, then optimize. | ||
| HeadersSyncParams ComputeHeadersSyncParams(std::chrono::seconds timespan, int64_t minchainwork_headers) |
There was a problem hiding this comment.
nanonit: Could keep to the name in Consensus::Params:
| // the chain's age and minimum-chain-work header count, then optimize. | |
| HeadersSyncParams ComputeHeadersSyncParams(std::chrono::seconds timespan, int64_t minchainwork_headers) | |
| // the chain's age and minimum-chain-work height, then optimize. | |
| HeadersSyncParams ComputeHeadersSyncParams(std::chrono::seconds timespan, int64_t minchainwork_height) |
| // alternate chain. This trade-off is ignored here, as it results in at most a small constant | ||
| // factor in attack rate. | ||
|
|
||
| HeadersSyncParams ComputeHeadersSyncParamsInner(int64_t max_headers, int64_t minchainwork_headers, double attack_headers) |
There was a problem hiding this comment.
nit: How about swapping the function definition order for ComputeHeadersSyncParams() & ComputeHeadersSyncParamsInner() to match the order in the header?
In order to attempt understanding the attack_headers argument coming in it's helpful to at least have glimpsed at the body of ComputeHeadersSyncParams().
| * 6 Gbit/s is approximately the speed at which a single thread of a Ryzen 5950X CPU thread can | ||
| * hash headers. In practice, the victim's network bandwidth and network processing overheads | ||
| * probably impose a far lower number, but it's a useful upper bound. */ | ||
| constexpr double ATTACK_BANDWIDTH{6000000000.0}; |
There was a problem hiding this comment.
nanonit: Helps human eyes:
| constexpr double ATTACK_BANDWIDTH{6000000000.0}; | |
| constexpr double ATTACK_BANDWIDTH{6'000'000'000.0}; |
| /** How much additional permanent memory usage are attackers (jointly) allowed to cause in the | ||
| * victim, expressed as fraction of the normal memory usage due to mainchain growth, for the | ||
| * duration the attack is sustained. [unitless]. 0.2 means that attackers, while they keep up the | ||
| * attack, can cause permanent memory usage due to headers storage to grow at 1.2 header per | ||
| * BLOCK_INTERVAL. */ | ||
| constexpr double ATTACK_FRACTION{0.2}; | ||
| /** How many bits a header uses in the P2P protocol: a block header, plus the trailing zero | ||
| * transaction count headers are relayed with. [bits] */ | ||
| constexpr int64_t NET_HEADER_SIZE{(sizeof(CBlockHeader) + 1) * 8}; | ||
| /** What rate of headers worth of RAM attackers are allowed to cause in the victim. [headers/s] */ | ||
| constexpr double LIMIT_HEADERRATE{ATTACK_FRACTION / BLOCK_INTERVAL}; | ||
| /** How many headers can attackers (jointly) send a victim per second. [headers/s] */ |
There was a problem hiding this comment.
Why jointly, isn't it more correct that multiple headers sync peers could be sending you these low-difficulty headers in parallel?
| /** How much additional permanent memory usage are attackers (jointly) allowed to cause in the | |
| * victim, expressed as fraction of the normal memory usage due to mainchain growth, for the | |
| * duration the attack is sustained. [unitless]. 0.2 means that attackers, while they keep up the | |
| * attack, can cause permanent memory usage due to headers storage to grow at 1.2 header per | |
| * BLOCK_INTERVAL. */ | |
| constexpr double ATTACK_FRACTION{0.2}; | |
| /** How many bits a header uses in the P2P protocol: a block header, plus the trailing zero | |
| * transaction count headers are relayed with. [bits] */ | |
| constexpr int64_t NET_HEADER_SIZE{(sizeof(CBlockHeader) + 1) * 8}; | |
| /** What rate of headers worth of RAM attackers are allowed to cause in the victim. [headers/s] */ | |
| constexpr double LIMIT_HEADERRATE{ATTACK_FRACTION / BLOCK_INTERVAL}; | |
| /** How many headers can attackers (jointly) send a victim per second. [headers/s] */ | |
| /** How much additional permanent memory usage is an attacking peer allowed to cause in the | |
| * victim, expressed as fraction of the normal memory usage due to mainchain growth, for the | |
| * duration the attack is sustained. [unitless]. 0.2 means that attackers, while they keep up the | |
| * attack, can cause permanent memory usage due to headers storage to grow at 1.2 header per | |
| * BLOCK_INTERVAL. */ | |
| constexpr double ATTACK_FRACTION{0.2}; | |
| /** How many bits a header uses in the P2P protocol: a block header, plus the trailing zero | |
| * transaction count headers are relayed with. [bits] */ | |
| constexpr int64_t NET_HEADER_SIZE{(sizeof(CBlockHeader) + 1) * 8}; | |
| /** What rate of headers worth of RAM attackers are allowed to cause in the victim. [headers/s] */ | |
| constexpr double LIMIT_HEADERRATE{ATTACK_FRACTION / BLOCK_INTERVAL}; | |
| /** How many headers can an attacking peer send a victim per second. [headers/s] */ |
There was a problem hiding this comment.
(To affect RAM usage the attacker(s) would need unique header chains for each peer but the difficulty could be timewarped to a minimum before forking).
There was a problem hiding this comment.
Yes, there may be multiple attackers in parallel. But their joint bandwidth to the victim is what matters, not their individual bandwidth.
The attack here consists of the attacker(s) sending the honest main chain during the commitment phase, and then giving a forged low-difficulty headers chain during the redownload phase. On average, for every attempt at this some tiny amount of these headers will be accepted into the blockchain index. If an someone could perform this attack an infinite number of times, our memory growth would be infinite too.
What saves us is that the attack costs download volume; each attack requires sending the entirety of the main chain's headers during a commitment phase. And we are okay with accepting a tiny amount of forged headers into our index, as long as that growth is sufficiently slow. After all, we're already okay with our blockchain index growing at a rate of ~1 block per 10 minutes. If all an attacker can do is increase that slightly (here, to 1.2 blocks per 10 minutes), then that's fine.
So the reasoning is: we accept that attacks are possible, and will be successful occasionally, but on average they cannot get more than a certain number of headers accepted per mainchain they send us. Since the attacker has a finite amount of bandwidth to us, that translates to a small finite amount of headers accepted per unit of time. As long as that is no more than 0.2 headers per 10 minutes, we are okay.
But what happens when there are multiple attackers, all performing the same attack on us? If each individual attacker was limited to 6 Gbit/s and our parameters are chosen so that a single 6 Gbit/s attacker could get 0.2 headers per 10 minutes accepted, then 1000 attackers doing the same thing in parallel could get 200 headers per 10 minutes accepted which would be totally unacceptable. However, this is not a concern: it's not each individual attacker that is limited to 6 Gbit/s, but all attackers combined. So, the 6 Gbit/s number must represent the joint bandwidth all attackers together have to us, which is indeed limited (our own network connection is a bound, as is the rate at which we can compute hashes).
There was a problem hiding this comment.
Thanks for the explanation! I must have glossed over the bandwidth applying to all attackers and become derailed by the single core CPU comment.
|
tACK 0316d0d Compiled from this branch, the two new functions return the exact optimum of their model for all five chains, every six hours from 2026-10-25 to 2041. The same holds on a grid of heights from 1 to 5 million and clocks, some before genesis. The chosen bufsize always meets the attack budget. Summing the attack model term by term, in exact arithmetic, gives the closed form for every period up to 16 and bufsize up to 60. I checked this with a Python port and a brute-force search; I can share the scripts as a gist. The new unit tests and p2p_headers_sync_with_minchainwork.py pass, and the parameters its nodes log match the port at each node's clock. At 2026-10-25 00:00 UTC the parameters, as period/bufsize, are mainnet 597/14697, testnet3 590/13096, testnet4 217/5604, signet 345/8770 and regtest 535/14517. Mainnet needs 689 KiB per peer against 722 KiB for the hard-coded 649/15400. On 2029-04-10, the date that pair was sized for, mainnet needs 14.7 KiB more than the pair, as you estimated. Testnet4 and signet fall much further, from 616/16199 and 629/15885, because each chain now uses its own genesis time, like HeadersSyncState's commitment bound when syncing from genesis. Rerunning the old script with 2009-01-03, mainnet's genesis date, reproduces all four hard-coded pairs. |
|
🐙 This pull request conflicts with the target branch and needs rebase. |
hodlinator
left a comment
There was a problem hiding this comment.
Did some pen & paper math to verify the quadratic derivation step for M. Nice to finally make use of that. :) Haven't taken a stab at the weighted average step and not completely understood the log2 part yet.
Firing off what I have so far FWIW since the review was started >1month ago. Sorry I'm not able to find more time for deep work.
| // - Not gratuitously preventing synchronizing any valid chain, however difficult such a chain may | ||
| // be to construct. In particular, the above scenario with an enormous timewarp-exploiting chain | ||
| // cannot simply be ignored, as it is legal that the honest main chain is like that. We however | ||
| // do not bother minimizing the memory usage in that case (because a billion-header long honest | ||
| // chain will inevitably use far larger amounts of memory than designed for). |
There was a problem hiding this comment.
One might add that since we still require reaching the minchainwork limit, potential attackers able to reach that have a strong incentive to instead mine upon the honest chain.
| * Since the position of the first commitment is randomized, we need to average this expression | ||
| * over all F in [0, P-1]. Let K=floor(B/P), and M=(B mod P). Then we have: |
There was a problem hiding this comment.
remark: I considered whether it would simplify the math while still giving acceptable accuracy if we instead were always maximally pessimistic and assumed that the attacker is lucky enough to have the first commitment position at P-1. Clanker responded negatively.
| * with solution | ||
| * | ||
| * [4*P - 1 +- sqrt(1 - 8*P^2 + 2^(K+4)*P * attack_headers)] / 2 | ||
| * = 2*P - 1/2 +- sqrt(1/4 - 2*P^2 + 2^(K+2)*P * attack_headers) |
There was a problem hiding this comment.
Could include M?
| * with solution | |
| * | |
| * [4*P - 1 +- sqrt(1 - 8*P^2 + 2^(K+4)*P * attack_headers)] / 2 | |
| * = 2*P - 1/2 +- sqrt(1/4 - 2*P^2 + 2^(K+2)*P * attack_headers) | |
| * with solution for M = | |
| * | |
| * [4*P - 1 +- sqrt(1 - 8*P^2 + 2^(K+4)*P * attack_headers)] / 2 | |
| * = 2*P - 1/2 +- sqrt(1/4 - 2*P^2 + 2^(K+2)*P * attack_headers) |
| */ | ||
| const auto log2_attack_headers = std::log2(attack_headers); | ||
| const auto real_bufsize = [attack_headers, log2_attack_headers](double period) noexcept -> double { | ||
| const auto k = std::floor(std::log2(1.5 * period - 0.5) - log2_attack_headers); |
There was a problem hiding this comment.
Clanker helped clarify some undocumented steps for deriving this C++ expression like:
... upper bound for interval I haven't yet understood
=> attack_headers ≤ (2^−K*(3P−1)) / 2
=> 2^K ≤ (3P−1) / (2*attack_headers)
and then applying log2 on both sides.
Might be helpful to fill in the missing steps in the preceding comment or just above this line.
| /** How much additional permanent memory usage are attackers (jointly) allowed to cause in the | ||
| * victim, expressed as fraction of the normal memory usage due to mainchain growth, for the | ||
| * duration the attack is sustained. [unitless]. 0.2 means that attackers, while they keep up the | ||
| * attack, can cause permanent memory usage due to headers storage to grow at 1.2 header per | ||
| * BLOCK_INTERVAL. */ | ||
| constexpr double ATTACK_FRACTION{0.2}; | ||
| /** How many bits a header uses in the P2P protocol: a block header, plus the trailing zero | ||
| * transaction count headers are relayed with. [bits] */ | ||
| constexpr int64_t NET_HEADER_SIZE{(sizeof(CBlockHeader) + 1) * 8}; | ||
| /** What rate of headers worth of RAM attackers are allowed to cause in the victim. [headers/s] */ | ||
| constexpr double LIMIT_HEADERRATE{ATTACK_FRACTION / BLOCK_INTERVAL}; | ||
| /** How many headers can attackers (jointly) send a victim per second. [headers/s] */ |
There was a problem hiding this comment.
Thanks for the explanation! I must have glossed over the bandwidth applying to all attackers and become derailed by the single core CPU comment.

This migrates the headers presync parameters (
commitment_periodandredownload_buffer_size) from being precomputed chainparams to being computed at runtime whenever a headers sync starts. This has as advantages:contrib/devtools/headerssync-params.pyscript.To achieve this, the parameter search algorithm is implemented in C++. It is simpler, because it does not attempt to model the fact that the attacker is forced to submit their headers in batches of 2000 if they want to maintain the attack. The old Python code did that, but actually got it (slightly) wrong by missing the fact that attackers are capable of strategically deciding to stop the attack in the middle of a batch (found by darosior).
Unit tests and fuzz tests are added, and at the end the old Python code is deleted.