nostr_tools.sanitize

nostr_tools.sanitize(value)[source]

Sanitize values by removing null bytes and recursively cleaning data structures.

This function removes null bytes (x00) from strings and recursively processes lists and dictionaries to ensure all contained data is sanitized. Null bytes can cause issues with event validation and relay communication.

The function handles: - Strings: Removes x00 null bytes - Lists: Recursively sanitizes all elements - Dictionaries: Recursively sanitizes both keys and values - Other types: Returns unchanged

Parameters:

value (Any) – Value to sanitize. Can be str, list, dict, or any other type.

Returns:

Sanitized value with null bytes removed from all strings.

Type is preserved (str returns str, list returns list, etc.).

Return type:

Any

Examples

Sanitize a string:

>>> text = "Hello\x00World"
>>> clean = sanitize(text)
>>> print(clean)
HelloWorld

Sanitize nested structures:

>>> data = {
...     "content": "Test\x00message",
...     "tags": [["e", "id\x00123"], ["p", "abc"]]
... }
>>> clean_data = sanitize(data)
>>> print(clean_data)
{'content': 'Testmessage', 'tags': [['e', 'id123'], ['p', 'abc']]}

Use with event data:

>>> event_dict = {
...     "content": user_input,  # May contain null bytes
...     "tags": user_tags
... }
>>> sanitized = sanitize(event_dict)
>>> event = Event.from_dict(sanitized)  # Now safe to validate