From d30c1bff46db78fb0c85b0ff5537f1164446a65b Mon Sep 17 00:00:00 2001 From: fiatjaf Date: Sat, 14 Feb 2026 22:34:16 -0300 Subject: [PATCH] khatru/policies: PreventNormalDuplicates() --- khatru/policies/events.go | 53 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/khatru/policies/events.go b/khatru/policies/events.go index a42f448..eca5f16 100644 --- a/khatru/policies/events.go +++ b/khatru/policies/events.go @@ -3,6 +3,7 @@ package policies import ( "context" "fmt" + "iter" "regexp" "slices" "strings" @@ -144,3 +145,55 @@ func RejectUnprefixedNostrReferences(ctx context.Context, event nostr.Event) (bo return false, "" } + +// PreventNormalDuplicates prevents normal events that refer to the same thing from being saved. +// For kinds 6, 7, 16, 1018 it checks "e" tags. +// For kind 1163 it checks "p" tags. +// For kinds 1163, 6, 16, 7516, 7517 it checks "a" tags. +func PreventNormalDuplicates(query func(nostr.Filter, int) iter.Seq[nostr.Event]) func(ctx context.Context, event nostr.Event) (bool, string) { + exists := func(event nostr.Event, tagName string) bool { + hasAll := true + for e := range event.Tags.FindAll("e") { + hasThis := false + for range query(nostr.Filter{ + Authors: []nostr.PubKey{event.PubKey}, + Kinds: []nostr.Kind{event.Kind}, + Tags: nostr.TagMap{"e": []string{e[1]}}, + }, 1) { + hasThis = true + } + if !hasThis { + hasAll = false + break + } + } + return hasAll + } + + return func(ctx context.Context, event nostr.Event) (bool, string) { + reject := false + + switch event.Kind { + case 6: + reject = exists(event, "e") && exists(event, "a") + case 7: + reject = exists(event, "e") + case 16: + reject = exists(event, "e") && exists(event, "a") + case 1018: + reject = exists(event, "e") + case 1163: + reject = exists(event, "p") + case 7516: + reject = exists(event, "a") + case 7517: + reject = exists(event, "a") + } + + if reject { + return true, "an event similar to this already exists" + } + + return false, "" + } +}