package nostr import ( "fmt" "github.com/nbd-wtf/go-nostr" "github.com/nbd-wtf/go-nostr/nip19" ) // Naddr represents a parsed naddr (Nostr addressable event reference) type Naddr struct { Kind int Pubkey string DTag string Relays []string RawNaddr string } // ParseNaddr decodes a bech32-encoded naddr string and extracts its components // Uses the go-nostr library's nip19.Decode which supports longer naddr strings func ParseNaddr(naddr string) (*Naddr, error) { // Use go-nostr's nip19.Decode which handles longer strings via DecodeNoLimit prefix, value, err := nip19.Decode(naddr) if err != nil { return nil, fmt.Errorf("failed to decode naddr: %w", err) } if prefix != "naddr" { return nil, fmt.Errorf("invalid naddr prefix: expected 'naddr', got '%s'", prefix) } // Cast to EntityPointer ep, ok := value.(nostr.EntityPointer) if !ok { return nil, fmt.Errorf("failed to parse naddr: unexpected type") } if ep.Kind == 0 { return nil, fmt.Errorf("naddr missing kind") } if ep.PublicKey == "" { return nil, fmt.Errorf("naddr missing pubkey") } if ep.Identifier == "" { return nil, fmt.Errorf("naddr missing d tag") } return &Naddr{ Kind: ep.Kind, Pubkey: ep.PublicKey, DTag: ep.Identifier, Relays: ep.Relays, RawNaddr: naddr, }, nil } // ToEventReference converts the naddr to an event reference string (kind:pubkey:d) func (n *Naddr) ToEventReference() string { return fmt.Sprintf("%d:%s:%s", n.Kind, n.Pubkey, n.DTag) } // ToFilter creates a nostr filter for this naddr func (n *Naddr) ToFilter() nostr.Filter { return nostr.Filter{ Kinds: []int{n.Kind}, Authors: []string{n.Pubkey}, Tags: map[string][]string{ "d": {n.DTag}, }, } } // CreateNaddr creates a bech32-encoded naddr from kind, pubkey, dtag, and optional relays func CreateNaddr(kind int, pubkey string, dtag string, relays []string) (string, error) { // nip19.EncodeEntity signature: (publicKey string, kind int, identifier string, relays []string) naddr, err := nip19.EncodeEntity(pubkey, kind, dtag, relays) if err != nil { return "", fmt.Errorf("failed to encode naddr: %w", err) } return naddr, nil }