def _decode_auth(encoded_packet: bytes) -> Tuple[Union[AuthHeader, Nonce], int]: try: decoded_auth, _, message_start_index = rlp.codec.consume_item(encoded_packet, TAG_SIZE) except DecodingError as error: raise ValidationError("Packet authentication section is not proper RLP") from error if is_bytes(decoded_auth): validate_nonce(decoded_auth) return Nonce(decoded_auth), message_start_index elif is_list_like(decoded_auth): validate_length(decoded_auth, 5, "auth header") for index, element in enumerate(decoded_auth): if not is_bytes(element): raise ValidationError(f"Element {index} in auth header is not bytes: {element}") auth_header = AuthHeader( auth_tag=decoded_auth[0], id_nonce=decoded_auth[1], auth_scheme_name=decoded_auth[2], ephemeral_public_key=decoded_auth[3], encrypted_auth_response=decoded_auth[4], ) validate_auth_header(auth_header) return auth_header, message_start_index else: raise Exception("unreachable: RLP can only encode bytes and lists")
def validate_auth_header(auth_header: AuthHeader) -> None: validate_nonce(auth_header.auth_tag) if auth_header.auth_scheme_name != AUTH_SCHEME_NAME: raise ValidationError( f"Auth header uses scheme {auth_header.auth_scheme_name!r}, but only " f"{AUTH_SCHEME_NAME!r} is supported") validate_length(auth_header.id_nonce, ID_NONCE_SIZE, "id nonce")
def _decode_who_are_you_payload(encoded_packet: bytes) -> Tuple[Nonce, IDNonce, int]: payload_rlp = encoded_packet[MAGIC_SIZE:] try: payload = rlp.decode(payload_rlp) except DecodingError as error: raise ValidationError( f"WHOAREYOU payload section is not proper RLP: {encode_hex(payload_rlp)}" ) from error if not is_list_like(payload): raise ValidationError( f"WHOAREYOU payload section is not an RLP encoded list: {payload}" ) if len(payload) != 3: raise ValidationError( f"WHOAREYOU payload consists of {len(payload)} instead of 3 elements: {payload}" ) token, id_nonce, enr_seq_bytes = payload enr_seq = big_endian_int.deserialize(enr_seq_bytes) validate_nonce(token) return Nonce(token), id_nonce, enr_seq
def validate_auth_header(auth_header: AuthHeader) -> None: validate_nonce(auth_header.auth_tag) if auth_header.auth_scheme_name != AUTH_SCHEME_NAME: raise ValidationError( f"Auth header uses scheme {auth_header.auth_scheme_name}, but only " f"{AUTH_SCHEME_NAME} is supported")
def test_nonce_validation_valid(key): validate_nonce(Nonce(key))
def test_nonce_validation_invalid(): for length in (0, 11, 13, 16): with pytest.raises(ValidationError): validate_nonce(Nonce(b"\x00" * length))