struct has many issues in messages.py:
- For unpacking, it requires to specify the length a second time, even when it is already clear from the
f.read(num_bytes)context. - For unpacking, it is designed to support a long format string and returning a tuple of many values. However, except for 3 instances in
messages.py, usually only a single value is unpacked and all those cases require an[0]access. - For packing and unpacking of a single value, the format string consists of characters that may be confusing and may need to be looked up in the documentation, as opposed to using easy to understand self-documenting code.
I presume the above issues lead to accidentally treat msg_version.relay as a "signed bool", which is fine, but confusing.
Fix all issues by using the built-in int helpers to_bytes and from_bytes via a scripted diff.
Review notes:
struct.unpackthrows an error if the number of bytes passed is incorrect.int.from_bytesdoesn't know about "missing" bytes and treats an empty byte array asint(0). "Extraneous" bytes should never happen, because allreadcalls are limited in this file. If it is important to keep this error behavior, a helperint_from_stream(stream, num_bytes, bytes, byteorder, *, **kwargs)can be added, which checks the number of bytes read from the stream.- For
struct.packandint.to_bytesthe error behavior is the same, although the error messages are not identical.