nostr_tools.to_hex¶
- nostr_tools.to_hex(bech32_str)[source]¶
Convert a Bech32 encoded string to hexadecimal format.
This function decodes a Bech32 string (npub, nsec, note, etc.) and returns the underlying data as a hexadecimal string. Useful for converting user-friendly Bech32 identifiers back to hex format for protocol use.
- Parameters:
bech32_str (
str) – The Bech32 encoded string to convert. Examples: npub1…, nsec1…, note1…- Returns:
- The hexadecimal encoded string (typically 64 characters).
Returns empty string if decoding fails.
- Return type:
Examples
Decode public key:
>>> npub = "npub1..." >>> pubkey_hex = to_hex(npub) >>> len(pubkey_hex) 64
Decode private key:
>>> nsec = "nsec1..." >>> privkey_hex = to_hex(nsec) >>> # Use privkey_hex for signing
Decode event ID:
>>> note_id = "note1..." >>> event_id_hex = to_hex(note_id) >>> # Use event_id_hex to fetch event
Convert user input:
>>> user_input = input("Enter npub: ") # User enters npub1... >>> pubkey = to_hex(user_input) >>> if pubkey: ... filter = Filter(authors=[pubkey])
Round-trip conversion:
>>> original_hex = "abc123..." # 64-char hex >>> bech32 = to_bech32('npub', original_hex) >>> decoded_hex = to_hex(bech32) >>> assert original_hex == decoded_hex
Handle invalid input:
>>> result = to_hex("invalid-bech32") >>> if not result: ... print("Invalid Bech32 string")