A BitTorrent client
Stage 6 of 12v2 · 3f9914d2

Peer handshake

Build and validate all 68 peer-handshake bytes, including the expected infohash.

Peer handshake

Build and validate all 68 peer-handshake bytes, including the expected infohash. The implementation is cumulative and must preserve earlier operations.

Observable contract

The harness reads JSON and represents binary data as hexadecimal. Tracker and peer replies are supplied as fixtures to avoid external networking and randomness.

{
  "op": "handshake-fields",
  "protocol": "BitTorrent protocol",
  "reservedHex": "0000000000000000",
  "infoHashHex": "0000000000000000000000000000000000000000",
  "peerId": "-SC0001-abcdefghijkl"
}

produces exactly:

{ "length": 68, "protocolLength": 19 }

Emit compact JSON and a final newline. Invalid requests leave stdout empty, include error on stderr, and exit non-zero.

Implementation

Keep binary data as bytes: do not turn hashes, peer IDs, or pieces into text except where the protocol says so. Separate framing, peer state, scheduling, and integrity. Verify lengths and hashes before publishing a piece as complete.

Walk through the fixture by offsets and test fragmentation, duplicate messages, timeouts, and peers advertising inconsistent data. Tests do not use the Internet; connect the same logic to real sockets outside the harness.

Acceptance criteria

  • The representative case produces the exact output.
  • No unverified data reaches the final file.
  • Scheduling is deterministic for the same input.