Fix the Fletcher checksum check for packets

Review the AI's codeEasy12 min

Your task

Your packets end with a 2-byte checksum. The first verifier summed the body bytes, so a packet with two bytes swapped, or one byte up and another down by the same amount, still passed. The fix uses Fletcher-16, which also weighs each byte by its position.

An assistant wrote verify_packet(packet). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • packet: the packet's bytes, as integers from 0 to 255. The last 2 are the checksum, high byte first. The rest is the body.
  • Return true when the checksum matches the body, else false.

Rules the tests check:

  • A packet shorter than 2 bytes has no checksum: return false.
  • The claimed checksum is the first checksum byte times 256, plus the second.
  • Fletcher-16: start with sum1 = 0 and sum2 = 0. For each body byte in order, set sum1 = (sum1 + byte) mod 255, then sum2 = (sum2 + sum1) mod 255.
  • The computed checksum is sum2 times 256, plus sum1. The packet is valid when it equals the claimed checksum.

Examples

verify_packet(packet: list[int]) -> bool
Example 1
Inputverify_packet([1, 2, 3, 10, 6])
OutputTrue
Example 2
Inputverify_packet([3, 2, 1, 10, 6])
OutputFalse
Example 3
Inputverify_packet([0, 0])
OutputTrue