package nostr import ( "encoding/json" "errors" "fmt" "net/http" "strings" "git.minhas.io/asara/well-goknown/lnd" "git.minhas.io/asara/well-goknown/redis" "github.com/davecgh/go-spew/spew" "github.com/nbd-wtf/go-nostr/nip19" ) type nostrWellKnown struct { Names map[string]string `json:"names"` Relays map[string][]string `json:"relays,omitempty"` } type NostrRequest struct { Name string `json:"name"` Key string `json:"key"` Hostname string Relays []string `json:"relays,omitempty"` } func RequestNostrAddr(w http.ResponseWriter, r *http.Request) { switch r.Method { case "GET": http.ServeFile(w, r, "nostr/form.html") case "POST": r.ParseForm() relays := make(map[string][]string) npub := r.FormValue("Key") // convert npub to hex hexKey, err := convertNpubtoHex(npub) if err != nil { w.WriteHeader(http.StatusBadRequest) return } names := map[string]string{r.FormValue("Name"): hexKey} user := nostrWellKnown{} if r.FormValue("Relays") != "" { relays = map[string][]string{ hexKey: strings.Split(r.FormValue("Relays"), ","), } user = nostrWellKnown{Names: names, Relays: relays} } else { user = nostrWellKnown{Names: names} } jsonUser, _ := json.Marshal(user) paymentReq, exp, err := lnd.Request(jsonUser) if err != nil { w.WriteHeader(http.StatusServiceUnavailable) return } spew.Dump(paymentReq) spew.Dump(exp) } } func GetNostrAddr(w http.ResponseWriter, r *http.Request) { // get query string for username r.ParseForm() // connect to redis redis, err := redis.New("localhost:6379", "", redis.NostrDb) if err != nil { w.WriteHeader(http.StatusNotFound) return } requestedName := r.FormValue("name") // search for user@domain search := fmt.Sprintf("%s@%s", requestedName, getHostname(r.Host)) addr, err := redis.Client.Get(search).Result() if err != nil { w.WriteHeader(http.StatusNotFound) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) fmt.Fprintf(w, addr) } func AddNostrAddr(n NostrRequest) { // transform request to well known struct relays := make(map[string][]string) user := nostrWellKnown{} names := map[string]string{n.Name: n.Key} if n.Relays != nil { relays = map[string][]string{n.Key: n.Relays} user = nostrWellKnown{Names: names, Relays: relays} } else { user = nostrWellKnown{Names: names} } jsonUser, _ := json.Marshal(user) r, err := redis.New("localhost:6379", "", redis.NostrDb) if err != nil { fmt.Println("FAILED") } nameKey := fmt.Sprintf("%s@%s", n.Name, n.Hostname) err = r.Client.Set(nameKey, jsonUser, redis.NostrDb).Err() if err != nil { fmt.Println("FAILED") } } func getHostname(hostname string) string { // remove port for local testing if strings.Contains(hostname, ":") { hostname = strings.Split(hostname, ":")[0] } return hostname } func convertNpubtoHex(npub string) (string, error) { if !strings.HasPrefix(npub, "npub1") { return "", errors.New("Not an npub key") } _, hex, err := nip19.Decode(npub) if err != nil { spew.Dump(hex) } return hex.(string), nil }