From 6f5737a763eabdf8e58159d945ccb9bc63ffd48c Mon Sep 17 00:00:00 2001 From: fiatjaf Date: Thu, 13 Feb 2025 23:05:39 -0300 Subject: [PATCH] pointers from tags helpers. --- pointers.go | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/pointers.go b/pointers.go index 6436cb3..93d605a 100644 --- a/pointers.go +++ b/pointers.go @@ -2,6 +2,8 @@ package nostr import ( "fmt" + "strconv" + "strings" ) type Pointer interface { @@ -15,6 +17,23 @@ type ProfilePointer struct { Relays []string `json:"relays,omitempty"` } +func ProfilePointerFromTag(refTag Tag) (ProfilePointer, error) { + pk := (refTag)[1] + if !IsValidPublicKey(pk) { + return ProfilePointer{}, fmt.Errorf("invalid pubkey '%s'", pk) + } + + pointer := ProfilePointer{ + PublicKey: pk, + } + if len(refTag) > 2 { + if relay := (refTag)[2]; IsValidRelayURL(relay) { + pointer.Relays = []string{relay} + } + } + return pointer, nil +} + func (ep ProfilePointer) MatchesEvent(_ Event) bool { return false } func (ep ProfilePointer) AsTagReference() string { return ep.PublicKey } @@ -32,6 +51,26 @@ type EventPointer struct { Kind int `json:"kind,omitempty"` } +func EventPointerFromTag(refTag Tag) (EventPointer, error) { + id := (refTag)[1] + if !IsValid32ByteHex(id) { + return EventPointer{}, fmt.Errorf("invalid id '%s'", id) + } + + pointer := EventPointer{ + ID: id, + } + if len(refTag) > 2 { + if relay := (refTag)[2]; IsValidRelayURL(relay) { + pointer.Relays = []string{relay} + } + if len(refTag) > 3 && IsValidPublicKey((refTag)[3]) { + pointer.Author = (refTag)[3] + } + } + return pointer, nil +} + func (ep EventPointer) MatchesEvent(evt Event) bool { return evt.ID == ep.ID } func (ep EventPointer) AsTagReference() string { return ep.ID } @@ -53,6 +92,34 @@ type EntityPointer struct { Relays []string `json:"relays,omitempty"` } +func EntityPointerFromTag(refTag Tag) (EntityPointer, error) { + spl := strings.SplitN(refTag[1], ":", 3) + if len(spl) != 3 { + return EntityPointer{}, fmt.Errorf("invalid addr ref '%s'", refTag[1]) + } + if !IsValidPublicKey(spl[1]) { + return EntityPointer{}, fmt.Errorf("invalid addr pubkey '%s'", spl[1]) + } + + kind, err := strconv.Atoi(spl[0]) + if err != nil || kind > (1<<16) { + return EntityPointer{}, fmt.Errorf("invalid addr kind '%s'", spl[0]) + } + + pointer := EntityPointer{ + Kind: kind, + PublicKey: spl[1], + Identifier: spl[2], + } + if len(refTag) > 2 { + if relay := (refTag)[2]; IsValidRelayURL(relay) { + pointer.Relays = []string{relay} + } + } + + return pointer, nil +} + func (ep EntityPointer) MatchesEvent(evt Event) bool { return ep.PublicKey == evt.PubKey && ep.Kind == evt.Kind &&