mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:44:38 +00:00
headersync: do parameter search at runtime #35642
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!35642
Loading…
Reference in a new issue
No description provided.
Delete branch "202607_headerssync_cpp"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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.
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
Reviewers, this pull request conflicts with the following ones:
src/and treat them as errors by hebasto)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.
Is there any anonymity breaking via
NodeClock::now()influencing these parameters? (I think maybe not, but might be worth quantizing or similar to guarantee it?)Good point, I had not considered that.
The choice of the commitment period should not be observable (besides a very minor time leak perhaps). However, the redownload buffer is observable in that an attacker can probably disconnect mid-redownload, and see how much you accepted afterwards.
I'll run some numbers to see how quickly these parameters change and suggest some quantization or noise.
It looks like the output parameters only change roughly every 22 days. I don't think quantizing further gains us much, especially as the attack only applies during IBD, so peers generally already know you just started.
Could turn into draft while CI is red?
Somehow
mocdoesn't like the changes tonet_processing.hthis makes, but only in the sanitizer build?Concept ACK
🐙 This pull request conflicts with the target branch and needs rebase.
Approach ACK ; needs rebase if wanted for 32.0 I guess?
Concept ACK
Rebased.
next_heighthere isint, whilem_current_heightisint64_tandValidateAndStoreRedownloadedHeaderusesint64_tfor the same step. For the long timewarp chains you mention, the presync height can exceedINT_MAXand overflow. Not a practical concern, but it should probably beint64_tto match the redownload path?@shuv-amp That's mostly independent of this PR, but added a commit to address that. I have also made a small simplification in the search algorithm.
Ready for more review.
ComputeHeadersSyncParams()doesn't terminate for a smallminchainwork_headerscombined with a short timespan:
30229 is the boundary; below it the region extends out to timespans around 1e4 s.
In
attack_rate(), the left side offuture_limit * prob < 1.0e-16 * ratecan't benegative, and the right side is exactly 0 once
rateis below ~2.5e-308, so thatbreak stops being reachable. The
limitcheck is the only other exit and Step 1'sNewton call doesn't pass one, so there it has none at all.
The Python this replaces has the same shape
(
HEADER_BATCH_COUNT * prob < 1.0e-16 * rate * len(align_choices)) and doesn'tterminate at those arguments either, so it isn't new, it just matters more now that
it runs at startup.
Non-strict is enough, since
probdecreases to exactly 0 and takes the left sidewith it:
The 50 test vectors still reproduce with that, and 196/196 other inputs I compared
are unchanged.
Nothing in chainparams is close: testnet4 has the lowest
minchainwork_heightat123613, and reaches an exponent of 531 against the 1075 where
probunderflows. Itis the region a new chain starts in though, and 0 hangs a different way
(
attack_headersis 0, soperiodis NaN andaccept_forged_headers > 0.0neverholds), so a guard on the input might be worth having too.
@shuv-amp Fixed, and added some extra
Assume()s in the code.I made a further simplification to the algorithm, and also added a fuzz test that exercises the code far beyond its intended parameter range, so catch meaningless results, crashes, or infinite loops. The fuzz tests are relatively slow (for extreme values it's just above 1/second, through normal running closer to 50/second), but it's also not a particularly large or complicated space to explore.
Concept ACK
🐙 This pull request conflicts with the target branch and needs rebase.
The
HeadersSyncParamsdefinition can now be moved from chainparams to the headersync module.Submitting my comments so far, because i think
attack_ratewill need to be revised.I think this routine underestimates the rate, because an incomplete batch sent by an attacker may be detected, but will still lead to processing as many headers from the buffer.
nit: feel free to ignore, just mentioning what gave me pause when i was reading from scratch.
That last sentence in the comment threw me off a little bit.
future_limitis a number of headers, weighted by the exponentially-decreasing contribution each batch makes. The last sentence could be read as it representing a single batch, while really it represents all batches, so the check later can be essentially "if the contribution of the entire tail of headers at the current probability is no more than a rounding error, we are done".nit:
forged_headerscounts the number of headers deviating from the honest chain up to that point (i.e. that batch and previous ones), whereasaccept_forged_headerscounts the additional number of headers accepted as the result of that batch. Took me a minute, and i think this could be clarified in the comment:Why is it not always true?
Why is this square root "indirection" necessary? Using
gamma = bufsize / period(intuitively "bits of security") andmemory_factor = (max_headers - mcw_headers) / COMPACT_HEADER_SIZEdirectly seem clearer to me, and equivalent?Converted to draft. @darosior found that the current version (and the original Python it's based on) did not take one attack scenario into account (using a final headers batch of size less than 2000). Fixing that is possible, but makes the code even more complicated, and results in parameters that increase per-peer memory by ~2.2 KiB.
I'm considering instead going for a much simpler approach, that drops the assumption that all headers arrive in batches of 2000 altogether. That'd be much simpler and faster, and perhaps more obviously correct, but increase per-peer memory by ~14.7 KiB. I think that's acceptable compared to existing memory usage.
Rewritten to take that approach. The commit history is simpler now too, as it doesn't attempt to show equivalence between the old Python script and the new code anymore.
🚧 At least one of the CI tasks failed.
Task
fuzzer,address,undefined,integer: https://github.com/bitcoin/bitcoin/actions/runs/35006193047/job/104506428335LLM reason (✨ experimental): Fuzz tests failed due to an UndefinedBehaviorSanitizer float-cast-overflow (inf cast to
int) inComputeHeadersSyncParamsInner(headersync.cpp:530).Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
ACK
526db3911dI was not familiar with the existing script, so i reviewed the new calculation from scratch. The latest approach is a lot easier to grasp. I think this slightly looser upper bound is the right tradeoff.
Is Step 2 really useful anymore with the new approach? It made sense when Step 1 was a Newton-Raphson search that stopped at some threshold, to use as a basis for a more accurate search. But now Step 1 is an exact (according to the model) derivation.
I asked Claude to check if Step 2 had any material impact in the new version. It claims that over 20,168 fuzz domain cases Step 2 picks offset 0 in 99.32% of cases. Furthermore, when it does pick a different offset it only saves about 0.0039% memory on realistic inputs.
I've changed it to only checking the
floor()andceil()of the continuous optimal period. Experimentally, the only examples where neither of those wins occur with extremely low security levels (they all involvebufsize<period).re-ACK
0e473d1752Neat.
🐙 This pull request conflicts with the target branch and needs rebase.
Earlier concerns remain unresolved; see the full report for their current assessments.
🟠 Minor · Avoid overflow when scaling negative timespans
headerssync.cpp:595 evaluates
6 * timespan.count()before the clamp, so a seconds count below INT64_MIN/6 overflows. NodeClock::now() asserts positive time and the fuzz target stays within ±(2^34-1), so no in-tree caller reaches it.Location:
src/headerssync.cpp:595(head).🟠 Minor · Use one clock sample for parameter sizing and the commitment cap
net_processing.cpp:2146 sizes the period from one Now() read, while headerssync.cpp:44 reads NodeClock::now() again for m_max_commitments. A host clock step between the two reads raises the commitment cap. The window is tiny and no clock-step producer is known.
Location:
src/net_processing.cpp:2144(head).🔵 Suggestion · The production-parameter wrapper lacks direct unit coverage
Unit tests do not pin the constants or clamp in
ComputeHeadersSyncParams, so a change could alter headers-sync parameters across networks without failing a test.Location:
src/test/headerssync_tests.cpp:236(head).🔵 Suggestion · The optimizer fuzz target does not check the attack-rate budget
The fuzz target checks only result shape, so a redownload buffer that exceeds the attack-rate budget outside the 50 unit vectors would pass its assertions.
Location:
src/test/fuzz/headerssync.cpp:171(head).🔵 Suggestion · The attack budget uses in-memory header size instead of wire size
The value is correct today, but an in-memory-only addition to
CBlockHeaderwould silently loosen the attack budget.Location:
src/headerssync.cpp:579(head).🔵 Suggestion · Initialize the minimum-chain-work height member
consensus/params.h:136 declares
int minchainwork_height;without a default initializer, so a default-constructed Consensus::Params leaves it indeterminate. Several other int members of the struct follow the same existing convention.Location:
src/consensus/params.h:133(head).Reviewed:
0316d0dc9ec6· Full review report · Previous reportsRebased, should be ready for review.
re-ACK
9f7bcfe874In practice, it is always true. Outside of that (fuzz tests) it could be untrue, so it's good to document under what conditions the function's behavior is well-defined.
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).
Since this assertion protects the test vectors (and since
ComputeHeadersSyncParamsInneris already very complicated), I’d keep it in the test.Move the test-vector size assertion
Following up on https://github.com/bitcoin/bitcoin/pull/35642#issuecomment-5297347941: is there a reason to use
Assume(rather thanAssert) for these preconditions? Shouldn't these abort in production? It seems to me that zero inputs could theoretically still lead to division by zero or an infinity-to-integer conversion.I wonder whether we need to find the optimum this precisely. If we restricted the buffer to whole commitment periods, we could calculate its size directly, and a logarithmic estimate might replace the period search too. The earlier experiments suggest a small memory increase could let us remove both searches. Do you think that tradeoff is worth exploring?
Whole-period calculation and earlier measurements
AI summary:
Unless I'm missing something, this could be simplified to modulo, see https://godbolt.org/z/53PfMqxnj.
If we cannot use that, could you add a same-line comment explaining why?
Use the remainder operator
Nit: I find the preceding
2^-K * ...form easier to follow. Could we separate the expected headers from the probability of passing the firstKchecks here?Separate the probability from the expected headers
Since
fail_buf = 2 * succ_buf + 1throughout the growth loop, we can grow justfail_bufinternally and derivesucc_bufat the end.Track one bound while growing the search range
Nit: The attack budget stays fixed during this search, so we could calculate its logarithm once in the capture.
Calculate the fixed logarithm once
Could we cap this loop? I was surprised we need a binary search here (considered a few alternatives but don't have a fully working version) and wondered about
NaNrisk, but that does actually make this condition break.Digging further with AI pointed to x87 excess precision: a midpoint can compare between the endpoints, then round back to one when stored, leaving the loop with no progress. GCC describes the relevant behavior.
Bound the existing bisection loop
The saved GCC 12.2/i686 runs timed out on the 50 existing vectors. The capped runs matched the native outputs. I inspected those results but have not rerun the compiler matrix.
Since we already have a
HeadersSyncParamstype could we move it and use it here as well (as @darosior also hinted I think)?Return the existing named parameter type
With the rewrite down to about 3 µs per call and fixed clocks already in these fuzz targets, is the override still worth keeping?
Use the existing fixed fuzz clocks
(Based on previous local suggestions, so this patch may not apply cleanly)
Nit: this only tests
ComputeHeadersSyncParamsInner(which doesn’t need the node setup), could we drop the fixture?Drop the unnecessary test fixture
Done.
I didn't take this, as it risks a disconnect between the two (e.g. a new
ExtraCompressedHeaderis introduced but only one of the two locations is updated to use it). Could be resolved by exporting the actually usedCOMPACT_HEADER_SIZE, and asserting on that in the test, but I feel that's overkill.It's true that the need for exactness is less relevant than in earlier iterations of this PR. But I still like the fact that it actually finds the optimal solution (within rounding precision) to a well-defined (but weakened) variant of the real problem, so a more naive search will find the exact same solutions.
To demonstrate that, I added a commit that does a more naive search on random inputs.
Done.
The reason for not doing this was my (folklore, perhaps) aversion due to division and modulus operators which are very slow instructions (as far as CPU instructions go; they used to be ~50s slower than multiplication IIRC).
Modern compilers don't need this, as will turn the computation of both a division and a modulus into a single instruction anyway, so I took your change.
Done.
Done.
Done.
Nice catch. Fixed, but with a much better alternative: do the bisection over integer
bufsizevalues, as those are the only ones we care about anyway. Avoids floating-point shenanigans like these, and is faster too.Done, in a later commit.
The reason for this approach (still kept in the first commit) is that doing it while such parameters are still defined in chainparams would need a cyclic dependency. With the later commit that removes them from chainparams, it's possible to move the
HeadersSyncParamsto headerssync.h.Done, and attributed.
Done.
Only had time for a quick pass and left a few questions. I'll review more carefully later.
Since this is the optimum for our simplified model of the attack surface, how much confidence do we have that the extra precision translates into a better tradeoff in practice?
Honest question, I'm still working on fully understanding it.
Could a slightly less memory-efficient result within that model be worth a simpler calculation, while preserving the same security bound?
I won't block either way, but the added complexity makes it harder for me to ACK confidently.
Nit: With the integer search, a zero height would give Step 2 invalid clamp bounds, so I would update this explanation. The earlier "real-valued" wording also helped me see that this formula allows fractional inputs.
Refresh the comments after the search rewrite
Thanks, please resolve
Nit: Now that both searches use integer bounds, we could use
std::midpointin both places.Use the standard midpoint helper
Would it make sense to encapsulate the bounds on legal periods in the search, so Step 2 can use its two candidates directly?
Try the two endpoints of the legal bracket
Nit: The caller uses the current time, even when the local tip is still genesis. I’d describe this as genesis-to-now.
Match the age description to its caller
Nit: I would find the failing period more useful than a failure count here. Initializing the best memory to the maximum also avoids treating the first iteration differently.
Report the period at a boundary failure
I forgot where, but you commented somewhere about simplifying to remove the need to search for bufsize.
It turns out that no simplification is needed, since we already have a closed-form function that finds the optimal bufsize when relaxed to real numbers (formerly
cont_bufsize, now renamed toreal_bufsize). The integer version doesn't need bisection, it can just roundreal_bufsizeup to an integer.This still leaves a bisection search for the periods. That one is harder to get rid of. It's possible to simplify the
attack_rateformula a bit more so the result can be found using a closed form expression with the Lambert W function, and evaluating that needs a loop still too. Simplifying it even further so that the solution can be written explicitly using just elementary functions would lose a great deal of accuracy.Done.
Done. Cool, I didn't know about
std::midpoint.Done.
Done.
I have dropped this commit, because
attack_rateis now gone entirely (see further). I could bring it back, with a test-only copy of the oldattack_ratecode if desirable, but it seems overkill now.Light ACK
02d1084ebaI'd appreciate another pair of eyes on the math.
The clock correction case still seems worth addressing here or in a follow-up, but isn't blocking for me, it's not systemic.
Thanks, please resolve
Similarly to #35208, could an incorrect startup clock leave us with an inflated memory allowance after the clock is corrected? Fresh nodes seem to skip the clock check against the stored chain tip for some reason:
github.com/bitcoin/bitcoin@02d1084eba/src/node/chainstate.cpp (L249-L255)According to my clanker, starting with a clock near the Unix epoch and correcting it before headers sync could leave the per-peer commitment allowance about 50x higher than intended - could we defer the estimate after the clock checks?
Nit: A few commit message and PR details my clankers found, just resolve if irrelevant:
Human linter comments for
02d1084ebaWill see if I find time to dig into the math.
Concept ACK!
nanonit: If you touch again, could const and brace-initialize to further tighten the screws (mutation+anti-narrowing verification).
This first section is somewhat duplicating the header:
github.com/bitcoin/bitcoin@4bacf21a13/src/headerssync.h (L59-L100)Could we refer to that instead, boil this down further, or merge them?
nit: Might as well use
static_assertmessage, and specify "case records".remark: "commitment phase" is clearer than "presync phase". Wish it was used everywhere in older code.
nit: This lambda could be declared inside
make_configto decrease cognitive complexity.Feels clearer explicitly capture here and for
make_config:Rather than magic numbers, could we use
sizeof(CBlockHeader)or compute it somehow, or improve the doc-string?80 is the value of
sizeof(CBlockHeader)but the 81 constant appears in headerssync-params.py on master. I would think it typically serializes down to something smaller due to compact integers, but then there is overhead for the network magic, message type etc?nanonit: It is used internally in production, as stated in the line above.
Would change it to:
While the comment is quite descriptive, I feel that it is sufficiently advanced that including the code for generating and filtering would be helpful for the next human needing update the record values. Maybe you consider the comment sufficient for LLMs and therefore not worth including dead code which harms code coverage stats?
Historically,
CBlockHeaderwas not a separate type, and headers were relayed asCBlock-with-0-transactions. That's where the value 81 comes from, and it is exact: there is just a trailing 0x00 byte at the end for the number of transactions.The overhead from the P2P transport (length/magic/command/checksum in V1, length/header/auth in V2) doesn't apply here because those are paid only once (and a single
headersmessage can carry 2000 of them).Ah, I see the tx count is ignored here at the end as you say:
github.com/bitcoin/bitcoin@4bacf21a13/src/net_processing.cpp (L5072-L5083)And none of the integers in
CBlockHeaderare serialized in compact form. So it is indeed exact.Still think it would be more helpful to have:
Done.
Done.
Reworded.
Nice catch. Changed to instead just compute the parameters at runtime per connection, now that it's super fast. The need to precompute it dated from when it was too slow to repeatedly recompute.
Explained in the comment now.
I don't think that's very helpful.
I've included the code in a comment, so it doesn't affect code coverage stats, but still allows re-running (or examining by an LLM for inspiration for future improvements).
I have made all captures explicit.
I've compacted the new text a bit.
Done.
lightly tested ACK
672e628d96Since 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.The release-process note and PR description could say that the parameters are computed at runtime whenever a headers sync begins - the current startup wording describes the previous implementation.
Align the wording with the current computation point
I'd find this easier to rerun as a script in
contrib/testgen/, with a reference here.That would also let Python tooling check it and keep the test easier to read.
Move the generator to contrib/testgen
Could we also validate these expected values against the attack-rate formula?
That would check the test records themselves, alongside checking that the optimizer reproduces them.
Check the buffer using the existing vectors
Done, and went further by implementing more checks to verify optimality of the test vectors.
I'm not taking this.
The test generator script isn't particularly important, it's just selecting some cases to try perhaps slightly better than purely randomly. There is no requirement that the test vectors match its output, or even that it's reproducible. Burdening the project with maintaining this code is overkill.
If you think it's undesirable to have this code in the comment, I'd rather delete it entirely and replace it with a single sentence explaining what considerations were made when generating the vectors.
Lightly tested diff re-ACK
0457cec22aThanks for considering, please resolve the suggestion.
Done.
reACK
0316d0dc9eFair point, but not going to touch this everywhere now.
nit: Decreasing the difficulty allows even faster hashing?
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_headersargument coming in it's helpful to at least have glimpsed at the body ofComputeHeadersSyncParams().nanonit: Could keep to the name in
Consensus::Params:nanonit: Helps human eyes:
Would expect
attack_headers => 1, butLIMIT_FRACTIONbecomes3.6000000000000005E-11. For amainchainwork_headersvalue of966143that makes theattack_headersparameter equal0.00003478....Going by the above comment, the number of headers sent by attackers that can at most be accepted by a victim is...
0.00003478...?! Does that mean zero attack headers are accepted? Or do we round it up to only 1 attack header?Would it be possible to better explain this in the comment?
Why jointly, isn't it more correct that multiple headers sync peers could be sending you these low-difficulty headers in parallel?
(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).
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.
Will address if I retouch.
Will address if I retouch.
Will address if I retouch.
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).
It's a fraction of headers accepted per header sent. 1 would be horrible, as it would mean every header sent by the attacker is accepted.
(disregard my now-deleted earlier comment, I missed you're already multiplying with
minchainwork_headers)The number is correct, in expectation. We permit 0.00003478 headers to be accepted per attack. That is, an attacker that performs the attack 1000000000 times, will on average get no more than 3478 headers accepted.
tACK
0316d0dc9eCompiled 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.
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.
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.
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.Could include M?
Clanker helped clarify some undocumented steps for deriving this C++ expression like:
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.
Thanks for the explanation! I must have glossed over the bandwidth applying to all attackers and become derailed by the single core CPU comment.