Nostr.NIP19.TLV (Nostr Lib v0.2.1)

View Source

Simple TLV (Type-Length-Value) encoding for NIP-19 shareable identifiers.

NIP-19 uses a simple TLV format where:

  • Type: 1 byte (uint8)
  • Length: 1 byte (uint8)
  • Value: L bytes

This is different from ASN.1 BER-TLV which uses variable-length tags and lengths.

TLV Types

  • 0 (special): depends on prefix - pubkey for nprofile, event_id for nevent, d-tag for naddr
  • 1 (relay): relay URL where entity is likely found (can repeat)
  • 2 (author): 32 bytes of event author pubkey
  • 3 (kind): 32-bit unsigned big-endian integer of event kind

Summary

Functions

TLV type for author pubkey

Decodes binary data into a list of TLV entries.

Encodes a single TLV entry to binary.

Encodes a list of TLV entries to binary.

Finds all values for a given TLV type in a list of entries.

Finds the first value for a given TLV type in a list of entries.

TLV type for event kind

TLV type for relay URLs

TLV type for special data (pubkey, event_id, or d-tag depending on prefix)

Types

tlv_entry()

@type tlv_entry() :: {tlv_type(), binary()}

tlv_type()

@type tlv_type() :: 0..255

Functions

author()

TLV type for author pubkey

decode_tlvs(data)

@spec decode_tlvs(binary()) :: {:ok, [tlv_entry()]} | {:error, :incomplete_tlv}

Decodes binary data into a list of TLV entries.

Per NIP-19 spec, unknown TLV types are ignored rather than causing errors.

Examples

iex> Nostr.NIP19.TLV.decode_tlvs(<<0, 2, 0xAB, 0xCD, 1, 5, "relay">>)
{:ok, [{0, <<0xAB, 0xCD>>}, {1, "relay"}]}

iex> Nostr.NIP19.TLV.decode_tlvs(<<0, 5, 0xAB>>)
{:error, :incomplete_tlv}

encode_tlv(type, value)

@spec encode_tlv(tlv_type(), binary()) :: binary()

Encodes a single TLV entry to binary.

Examples

iex> Nostr.NIP19.TLV.encode_tlv(0, <<0xCA, 0xFE>>)
<<0, 2, 0xCA, 0xFE>>

iex> Nostr.NIP19.TLV.encode_tlv(1, "wss://relay.example.com")
<<1, 23, "wss://relay.example.com">>

encode_tlvs(entries)

@spec encode_tlvs([tlv_entry()]) :: binary()

Encodes a list of TLV entries to binary.

Examples

iex> entries = [{0, <<0xAB, 0xCD>>}, {1, "relay"}]
iex> Nostr.NIP19.TLV.encode_tlvs(entries)
<<0, 2, 0xAB, 0xCD, 1, 5, "relay">>

find_all(entries, type)

@spec find_all([tlv_entry()], tlv_type()) :: [binary()]

Finds all values for a given TLV type in a list of entries.

Examples

iex> entries = [{0, "pubkey"}, {1, "relay1"}, {1, "relay2"}]
iex> Nostr.NIP19.TLV.find_all(entries, 1)
["relay1", "relay2"]

iex> Nostr.NIP19.TLV.find_all(entries, 2)
[]

find_first(entries, type)

@spec find_first([tlv_entry()], tlv_type()) :: binary() | nil

Finds the first value for a given TLV type in a list of entries.

Examples

iex> entries = [{0, "pubkey"}, {1, "relay1"}]
iex> Nostr.NIP19.TLV.find_first(entries, 0)
"pubkey"

iex> Nostr.NIP19.TLV.find_first(entries, 2)
nil

kind()

TLV type for event kind

relay()

TLV type for relay URLs

special()

TLV type for special data (pubkey, event_id, or d-tag depending on prefix)