test: p2p: check v1 magic bytes only after the full header #36730

Open
optout21 wants to merge 4 commits from 2611-testpython-v2-peer-fix into master AGit
optout21 commented 2026-11-02 12:39:44 +00:00 (Migrated from github.com)

Two test cases (p2p_v2_encrypted.py and p2p_v2_misbehaving.py) can fail in the -- improbable -- case when network reads happen to arrive in smaller chunks.

Related to #36726 .

All networking code using sockets must not make assumption about the chunking of the incoming/outgoing data, and should be resilient against any chunking. Normally, the chunking of the sends of the writer dictate the chunking of the receives at the reader, but this is not guaranteed by IP/TCP, intermediate networking elements may change the packet structure. In test using sockets on the same host, this is not very likely, but still possible.

Issues:

  • p2p_v2_encrypted.py: The v1 message parser in P2PConnection rejected the stream as soon as the first 4 bytes did not match the network magic. bitcoind's V1Transport::readHeader waits for the full 24-byte header before checking the magic.
    The v2 to v1 downgrade relies on bitcoind's behaviour: an outbound v2 connection is only retried with v1 (V2Transport::ShouldReconnectV1) if at least a v1 header's worth of bytes had been sent before the peer disconnected. If the node's first send reaches the test peer in small pieces, the Python peer could disconnect after just 4 bytes, the node would not retry with v1, and p2p_v2_encrypted.py would time out waiting for the reconnection.

  • p2p_v2_misbehaving.py: Fails for similar root cause. In this test, when the 64-byte key could not be read in one call, the empty array is indexed out-of-bounds, leading to a crash.

The issues were found -- and can be reproduced -- by using a reproducer patch, that forces all socket sends to use smaller chunking. For the run with the reproducer see #36724 .

The issues are test-code only, the non-test code is correct.

The fixes are:

  • p2p_v2_encrypted.py: Match bitcoind by checking the magic only once the full header has been received.

  • p2p_v2_misbehaving.py: Handle the short-read case explicitly, return the data read so far.

These fixes make the test more robust, even though a failure due to this issue in CI is very unlikely, but not impossible.

Two test cases (`p2p_v2_encrypted.py` and `p2p_v2_misbehaving.py`) can fail in the -- improbable -- case when network reads happen to arrive in smaller chunks. Related to #36726 . All networking code using sockets must not make assumption about the chunking of the incoming/outgoing data, and should be resilient against any chunking. Normally, the chunking of the sends of the writer dictate the chunking of the receives at the reader, but this is not guaranteed by IP/TCP, intermediate networking elements may change the packet structure. In test using sockets on the same host, this is not very likely, but still possible. Issues: - `p2p_v2_encrypted.py`: The v1 message parser in `P2PConnection` rejected the stream as soon as the first 4 bytes did not match the network magic. bitcoind's `V1Transport::readHeader` waits for the full 24-byte header before checking the magic. The v2 to v1 downgrade relies on bitcoind's behaviour: an outbound v2 connection is only retried with v1 (`V2Transport::ShouldReconnectV1`) if at least a v1 header's worth of bytes had been sent before the peer disconnected. If the node's first send reaches the test peer in small pieces, the Python peer could disconnect after just 4 bytes, the node would not retry with v1, and p2p_v2_encrypted.py would time out waiting for the reconnection. - `p2p_v2_misbehaving.py`: Fails for similar root cause. In this test, when the 64-byte key could not be read in one call, the empty array is indexed out-of-bounds, leading to a crash. The issues were found -- and can be reproduced -- by using a reproducer patch, that forces all socket sends to use smaller chunking. For the run with the reproducer see #36724 . The issues are test-code only, the non-test code is correct. The fixes are: - `p2p_v2_encrypted.py`: Match bitcoind by checking the magic only once the full header has been received. - `p2p_v2_misbehaving.py`: Handle the short-read case explicitly, return the data read so far. These fixes make the test more robust, even though a failure due to this issue in CI is very unlikely, but not impossible.
DrahtBot commented 2026-11-02 12:39:53 +00:00 (Migrated from github.com)

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.

Type Reviewers
ACK Pranav-error

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/36730 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36730.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36730#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | ACK | [Pranav-error](https://github.com/bitcoin/bitcoin/pull/36730#issuecomment-6845317673) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--5faf32d7da4f0f540f40219e4f7537a3-->
First-time contributor

🔵 Suggestion · Split-read fixes lack deterministic regression coverage

The functional tests do not force the receive boundaries and empty-garbage state needed to distinguish these fixes, so detecting regressions depends on incidental socket chunking.

Location: test/functional/test_framework/v2_p2p.py:141 (head).

Review coverage was incomplete.


Reviewed: ba7dde0b75fc · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:464886e574fc96b3587e582688c29b6bd7a73bba755cfc1d2f031cc648c7ec97:a99dfe27a5d9c587aaf93be1a4842812699d6122d1d9babba7210869336cc02c --> <!-- ralph-base:9183edd25e60aa410bc3e4728989a1d75c309a09 --> <!-- ralph-head:ba7dde0b75fce756d03dcb344d460387229b43cf --> <!-- ralph-case:f0cad2397cd2b7d98c225187dc00f617e758ad10584969f53e806d09ed3810a8 --> **🔵 Suggestion · Split-read fixes lack deterministic regression coverage** The functional tests do not force the receive boundaries and empty-garbage state needed to distinguish these fixes, so detecting regressions depends on incidental socket chunking. Location: [`test/functional/test_framework/v2_p2p.py:141`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/ba7dde0b75fce756d03dcb344d460387229b43cf/test/functional/test_framework/v2_p2p.py#L141>) (head). Review coverage was incomplete. <!-- Review tier: standard --> --- Reviewed: [`ba7dde0b75fc`](<https://git.fish.foo/bitcoin/bitcoin/commit/ba7dde0b75fce756d03dcb344d460387229b43cf>) · [Review report](<https://review.fish.foo/report/36730-ba7dde0b75fce756d03dcb344d460387229b43cf-2622-4.html>) · [Previous reports](<https://review.fish.foo/traces/36730/>) [permalink](<https://review.fish.foo/report/36730-ba7dde0b75fce756d03dcb344d460387229b43cf-2622-4.html>)
optout21 commented 2026-11-12 16:24:13 +00:00 (Migrated from github.com)

Added a fix for p2p_v2_misbehaving.py, for similar reasons (discovered in https://github.com/bitcoin/bitcoin/pull/36724#issuecomment-6822620427). In this test, when the 64-bytes key could not be read in one call, the empty array is indexed out-of-bounds, leading to a crash. The fix is to handle this case explicitly. (Updated description.)

Added a fix for `p2p_v2_misbehaving.py`, for similar reasons (discovered in https://github.com/bitcoin/bitcoin/pull/36724#issuecomment-6822620427). In this test, when the 64-bytes key could not be read in one call, the empty array is indexed out-of-bounds, leading to a crash. The fix is to handle this case explicitly. (Updated description.)
Pranav-error commented 2026-11-12 19:39:51 +00:00 (Migrated from github.com)

crACK be88a3b926

Reviewed the logic; both changes correctly handle partial reads in the test framework:

  • test_framework/p2p.py: deferring the v1 magic-bytes check until the full 24-byte header has arrived matches V1Transport, which only validates the header after reading all of it. Checked that nothing relies on the old early-raise: p2p_invalid_messages.py:test_magic_bytes drives the wrong-magic case from the sender side and asserts the node disconnects (Wrong MessageStart in the debug log), so it never depends on the harness raising at 4 bytes; the recvbuf[:4] == magic_bytes check in p2p_private_broadcast_retry_v1.py is a separate v1/v2-determination path and is unaffected.
  • p2p_v2_misbehaving.py: guarding the empty handshake_bytes return before random_bitflip(handshake_bytes[:16]) correctly propagates the "not all 64 ellswift bytes received yet" signal instead of bitflipping an empty slice.
crACK be88a3b926bd18d2243ca1a2e21332bca4f5d7e1 Reviewed the logic; both changes correctly handle partial reads in the test framework: - `test_framework/p2p.py`: deferring the v1 magic-bytes check until the full 24-byte header has arrived matches `V1Transport`, which only validates the header after reading all of it. Checked that nothing relies on the old early-raise: `p2p_invalid_messages.py:test_magic_bytes` drives the wrong-magic case from the sender side and asserts the *node* disconnects (`Wrong MessageStart` in the debug log), so it never depends on the harness raising at 4 bytes; the `recvbuf[:4] == magic_bytes` check in `p2p_private_broadcast_retry_v1.py` is a separate v1/v2-determination path and is unaffected. - `p2p_v2_misbehaving.py`: guarding the empty `handshake_bytes` return before `random_bitflip(handshake_bytes[:16])` correctly propagates the "not all 64 ellswift bytes received yet" signal instead of bitflipping an empty slice.
optout21 commented 2026-11-13 05:22:13 +00:00 (Migrated from github.com)

Added two more fixes. The issues surfaced here: https://github.com/bitcoin/bitcoin/pull/36724#issuecomment-6829802356.

  • p2p.py:

When P2PConnection is the v2 responder, _on_data_v2_handshake() used not self.v2_state.sent_garbage to decide whether it still had to send its ellswift key. The garbage length is random in [0, MAX_GARBAGE_LEN], so in about 1 in 4096 connections it is empty and the check stays true after the key has been sent.

If the peer's 64-byte key then arrives in more than one piece, complete_handshake() asks for more data, and on the next read the responder runs respond_v2_handshake() again: it generates and sends a second key, and misaligns the received key bytes. Both sides then wait for a garbage terminator that never comes. With the default long timeout nobody times out, and the test hangs until its own timeout.

The fix is to check whether our ellswift key has been generated instead.

  • v2_p2p: Return bytes consumed per call in respond_v2_handshake

respond_v2_handshake() returned len(self.received_prefix) as the number of bytes consumed, and the caller trims recvbuf by that amount. But received_prefix accumulates across calls, so when the v1 prefix check spans more than one read, too many bytes are dropped from recvbuf.

This happens when the peer's ellswift key starts with bytes that match the v1 prefix (e.g. the first network magic byte, about 1 in 256 keys) and a read ends inside that matching part. The remaining key bytes are then misaligned, the shared secret is wrong, and the handshake stalls.

The fix is to return only the number of bytes consumed in the current call.

Added two more fixes. The issues surfaced here: https://github.com/bitcoin/bitcoin/pull/36724#issuecomment-6829802356. - `p2p.py`: When `P2PConnection` is the `v2` responder, `_on_data_v2_handshake()` used `not self.v2_state.sent_garbage` to decide whether it still had to send its ellswift key. The garbage length is random in `[0, MAX_GARBAGE_LEN]`, so in about 1 in 4096 connections it is empty and the check stays true after the key has been sent. If the peer's 64-byte key then arrives in more than one piece, `complete_handshake()` asks for more data, and on the next read the responder runs `respond_v2_handshake()` again: it generates and sends a second key, and misaligns the received key bytes. Both sides then wait for a garbage terminator that never comes. With the default long timeout nobody times out, and the test hangs until its own timeout. The fix is to check whether our ellswift key has been generated instead. - `v2_p2p:` Return bytes consumed per call in respond_v2_handshake `respond_v2_handshake()` returned `len(self.received_prefix)` as the number of bytes consumed, and the caller trims `recvbuf` by that amount. But `received_prefix` accumulates across calls, so when the v1 prefix check spans more than one read, too many bytes are dropped from `recvbuf`. This happens when the peer's ellswift key starts with bytes that match the v1 prefix (e.g. the first network magic byte, about 1 in 256 keys) and a read ends inside that matching part. The remaining key bytes are then misaligned, the shared secret is wrong, and the handshake stalls. The fix is to return only the number of bytes consumed in the current call.
Pranav-error commented 2026-11-13 05:48:36 +00:00 (Migrated from github.com)

Tested ACK ba7dde0b75

Re-reviewed the two added fixes (updating my earlier crACK):

  • _on_data_v2_handshake: the "responder hasn't sent its key yet" guard now uses ellswift_ours is None instead of not sent_garbage. Correct — ellswift_ours starts None and is only set in generate_keypair_and_garbage (v2_p2p.py), so it reliably reflects whether the key was sent, whereas sent_garbage is falsy for the empty-garbage case (the ~1/4096 that re-ran the handshake and hung).
  • respond_v2_handshake: returning bytes consumed this call (len(received_prefix) - start_len) rather than the running total is right — received_prefix accumulates across split reads and the caller advances recvbuf by the returned length, so the total would over-advance on the second call.

Ran p2p_v2_misbehaving.py and p2p_v2_transport.py against a master build with this branch applied — both pass.

Tested ACK ba7dde0b75fce756d03dcb344d460387229b43cf Re-reviewed the two added fixes (updating my earlier crACK): - `_on_data_v2_handshake`: the "responder hasn't sent its key yet" guard now uses `ellswift_ours is None` instead of `not sent_garbage`. Correct — `ellswift_ours` starts `None` and is only set in `generate_keypair_and_garbage` (v2_p2p.py), so it reliably reflects whether the key was sent, whereas `sent_garbage` is falsy for the empty-garbage case (the ~1/4096 that re-ran the handshake and hung). - `respond_v2_handshake`: returning bytes consumed *this call* (`len(received_prefix) - start_len`) rather than the running total is right — `received_prefix` accumulates across split reads and the caller advances `recvbuf` by the returned length, so the total would over-advance on the second call. Ran `p2p_v2_misbehaving.py` and `p2p_v2_transport.py` against a master build with this branch applied — both pass.
optout21 commented 2026-11-13 10:14:11 +00:00 (Migrated from github.com)

Additional validation: The fix has been validated as well in a run with the reproducer, see https://github.com/bitcoin/bitcoin/pull/36724#issuecomment-6846132450
(current version ba7dde0b75)

Additional validation: The fix has been validated as well in a run with the reproducer, see https://github.com/bitcoin/bitcoin/pull/36724#issuecomment-6846132450 (current version ba7dde0b75fce756d03dcb344d460387229b43cf)
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!36730
No description provided.