Skip to content

Utils

A collection of utility functions designed to assist with NOSTR protocol tasks including key generation, event creation and signing, signature verification, Proof of Work (PoW), Bech32 encoding/decoding, URI validation, and relay URL extraction.

Calculate the event ID based on event parameters.

  • pubkey (str): The user’s public key in hex format.
  • created_at (int): Timestamp of the event creation.
  • kind (int): The event kind/type.
  • tags (list): List of tags associated with the event.
  • content (str): The main content of the event.
>>> calc_event_id('pubkey', 1234567890, 1, [['tag1', 'tag2']], 'Hello, World!')
'e41d2f51b631d627f1c5ed83d66e1535ac0f1542a94db987c93f758c364a7600'
  • str: SHA-256 hash (hexadecimal string) representing the event ID.
  • None

Sign an event ID using the private key.

  • event_id (str): Event ID to sign.
  • private_key_hex (str): Private key in hex format.
>>> sig_event_id('eventidhexstring', 'privatekeyhexstring')
'signaturehexstring'
  • str: The Schnorr signature as hex string.
  • None

Verify a signature for an event ID.

  • event_id (str): The event ID to verify.
  • pubkey (str): The public key in hex.
  • sig (str): The signature hex string.
>>> verify_sig('eventidhex', 'pubkeyhex', 'signaturehex')
True
  • bool: True if signature valid, False otherwise.
  • None

Generate an event with optional Proof of Work.

  • sec (str): Private key hex for signing.
  • pub (str): Public key hex.
  • kind (int): Event kind.
  • tags (list): Event tags.
  • content (str): Event content.
  • created_at (int | None): Timestamp (default now).
  • target_difficulty (int | None): PoW difficulty (leading zero bits).
  • timeout (int): Max seconds for PoW mining.
>>> generate_event('privkeyhex', 'pubkeyhex', 1, [['tag1']], 'Hello!')
  • dict: Event dictionary with id, pubkey, created_at, kind, tags, content, sig.
  • None

Generate a new NOSTR key pair.

  • tuple[str, str]: (private_key_hex, public_key_hex)

Test if private key matches the public key.

  • seckey (str): Private key hex.
  • pubkey (str): Public key hex.
  • bool: True if keys match, False otherwise.

Convert a hex string to Bech32.

  • prefix (str): Bech32 prefix (e.g. ‘nsec’, ‘npub’).
  • hex_str (str): Hexadecimal string to convert.
  • str: Bech32 encoded string.

Convert a Bech32 string back to hex.

  • bech32_str (str): Bech32 encoded string.
  • str: Hexadecimal string.

Extract WebSocket relay URLs from text.

  • text (str): Text containing URLs.
>>> find_websoket_relay_urls("Connect to wss://relay.example.com:443 and ws://relay.example.com")
['wss://relay.example.com:443', 'wss://relay.example.com']
  • list[str]: List of valid WebSocket relay URLs.

Sanitize strings or nested data structures by escaping null byte representations.

  • value (str|list|dict): Value to sanitize.
  • Sanitized version of the input with escaped null byte sequences.