wot-relay/main.go

288 lines
6.7 KiB
Go
Raw Normal View History

2024-09-06 11:16:40 -04:00
package main
import (
"context"
"fmt"
2024-09-06 19:25:40 -04:00
"html/template"
2024-09-06 11:16:40 -04:00
"log"
"net/http"
"os"
"sync"
"time"
"github.com/fiatjaf/eventstore/lmdb"
"github.com/fiatjaf/khatru"
"github.com/joho/godotenv"
"github.com/nbd-wtf/go-nostr"
)
type Config struct {
RelayName string
RelayPubkey string
RelayDescription string
DBPath string
2024-09-06 19:25:40 -04:00
RelayURL string
2024-09-06 19:33:29 -04:00
IndexPath string
StaticPath string
2024-09-06 11:16:40 -04:00
}
var archivePool *nostr.SimplePool
var fetchingPool *nostr.SimplePool
2024-09-06 11:16:40 -04:00
var relays []string
var config Config
var trustNetwork []string
var mu sync.Mutex
func main() {
fmt.Println("starting")
relay := khatru.NewRelay()
ctx := context.Background()
config = LoadConfig()
relay.Info.Name = config.RelayName
relay.Info.PubKey = config.RelayPubkey
relay.Info.Description = config.RelayDescription
appendPubkey(config.RelayPubkey)
2024-09-06 11:16:40 -04:00
db := lmdb.LMDBBackend{
Path: getEnv("DB_PATH"),
}
if err := db.Init(); err != nil {
panic(err)
}
relay.StoreEvent = append(relay.StoreEvent, db.SaveEvent)
relay.QueryEvents = append(relay.QueryEvents, db.QueryEvents)
relay.RejectEvent = append(relay.RejectEvent, func(ctx context.Context, event *nostr.Event) (bool, string) {
2024-09-06 17:39:39 -04:00
for _, pk := range trustNetwork {
2024-09-06 11:16:40 -04:00
if pk == event.PubKey {
return false, ""
}
}
return true, "you are not in the web of trust"
})
mu.Lock()
2024-09-06 11:16:40 -04:00
relays = []string{
"wss://nos.lol",
"wss://nostr.mom",
"wss://purplepag.es",
"wss://purplerelay.com",
"wss://relay.damus.io",
"wss://relay.mostr.pub",
"wss://relay.nos.social",
"wss://relay.nostr.band",
"wss://relay.snort.social",
"wss://relayable.org",
"wss://pyramid.fiatjaf.com",
"wss://relay.primal.net",
"wss://relay.nostr.bg",
"wss://no.str.cr",
"wss://nostr21.com",
"wss://nostrue.com",
"wss://relay.siamstr.com",
}
mu.Unlock()
2024-09-06 11:16:40 -04:00
go refreshTrustNetwork(relay, ctx)
go archiveTrustedNotes(relay, ctx)
2024-09-06 11:16:40 -04:00
2024-09-06 19:25:40 -04:00
mux := relay.Router()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles(os.Getenv("INDEX_PATH")))
data := struct {
RelayName string
RelayPubkey string
RelayDescription string
RelayURL string
}{
RelayName: config.RelayName,
RelayPubkey: config.RelayPubkey,
RelayDescription: config.RelayDescription,
RelayURL: config.RelayURL,
}
err := tmpl.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
2024-09-06 19:33:29 -04:00
mux.Handle("/favicon.ico", http.StripPrefix("/", http.FileServer(http.Dir(config.StaticPath))))
2024-09-06 19:25:40 -04:00
2024-09-06 11:16:40 -04:00
fmt.Println("running on :3334")
2024-09-06 19:38:39 -04:00
err := http.ListenAndServe(":3334", relay)
if err != nil {
log.Fatal(err)
}
2024-09-06 11:16:40 -04:00
}
func LoadConfig() Config {
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Error loading .env file")
}
config := Config{
RelayName: getEnv("RELAY_NAME"),
RelayPubkey: getEnv("RELAY_PUBKEY"),
RelayDescription: getEnv("RELAY_DESCRIPTION"),
DBPath: getEnv("DB_PATH"),
2024-09-06 19:25:40 -04:00
RelayURL: getEnv("RELAY_URL"),
2024-09-06 19:33:29 -04:00
IndexPath: getEnv("INDEX_PATH"),
StaticPath: getEnv("STATIC_PATH"),
2024-09-06 11:16:40 -04:00
}
return config
}
func getEnv(key string) string {
value, exists := os.LookupEnv(key)
if !exists {
log.Fatalf("Environment variable %s not set", key)
}
return value
}
func refreshTrustNetwork(relay *khatru.Relay, ctx context.Context) []string {
fetchingPool = nostr.NewSimplePool(ctx)
2024-09-06 11:16:40 -04:00
// Function to refresh the trust network
runTrustNetworkRefresh := func() {
2024-09-06 14:06:32 -04:00
timeoutCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
2024-09-06 11:16:40 -04:00
defer cancel()
filters := []nostr.Filter{{
Authors: []string{config.RelayPubkey},
Kinds: []int{nostr.KindContactList},
}}
for ev := range fetchingPool.SubManyEose(timeoutCtx, relays, filters) {
2024-09-06 11:16:40 -04:00
for _, contact := range ev.Event.Tags.GetAll([]string{"p"}) {
appendPubkey(contact[1])
}
}
chunks := make([][]string, 0)
for i := 0; i < len(trustNetwork); i += 100 {
end := i + 100
if end > len(trustNetwork) {
end = len(trustNetwork)
}
chunks = append(chunks, trustNetwork[i:end])
}
for _, chunk := range chunks {
threeTimeoutCtx, tenCancel := context.WithTimeout(ctx, 10*time.Second)
2024-09-06 11:16:40 -04:00
defer tenCancel()
filters = []nostr.Filter{{
Authors: chunk,
Kinds: []int{nostr.KindContactList},
}}
for ev := range fetchingPool.SubManyEose(threeTimeoutCtx, relays, filters) {
2024-09-06 11:16:40 -04:00
for _, contact := range ev.Event.Tags.GetAll([]string{"p"}) {
if len(contact) > 1 {
appendPubkey(contact[1])
} else {
fmt.Println("Skipping malformed tag: ", contact)
}
}
}
}
fmt.Println("trust network size:", len(trustNetwork))
getTrustNetworkProfileMetadata(relay, ctx)
}
runTrustNetworkRefresh()
ticker := time.NewTicker(10 * time.Minute)
defer ticker.Stop()
for range ticker.C {
runTrustNetworkRefresh()
2024-09-06 11:16:40 -04:00
}
return trustNetwork
}
func getTrustNetworkProfileMetadata(relay *khatru.Relay, ctx context.Context) {
2024-09-06 13:24:33 -04:00
chunks := make([][]string, 0)
for i := 0; i < len(trustNetwork); i += 100 {
end := i + 100
if end > len(trustNetwork) {
end = len(trustNetwork)
}
chunks = append(chunks, trustNetwork[i:end])
}
for _, chunk := range chunks {
timeoutCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
filters := []nostr.Filter{{
Authors: chunk,
Kinds: []int{nostr.KindProfileMetadata},
}}
for ev := range fetchingPool.SubManyEose(timeoutCtx, relays, filters) {
relay.AddEvent(ctx, ev.Event)
2024-09-06 13:24:33 -04:00
}
}
}
2024-09-06 11:16:40 -04:00
func appendPubkey(pubkey string) {
mu.Lock()
defer mu.Unlock()
for _, pk := range trustNetwork {
if pk == pubkey {
return
}
}
trustNetwork = append(trustNetwork, pubkey)
}
func archiveTrustedNotes(relay *khatru.Relay, ctx context.Context) {
2024-09-06 17:15:39 -04:00
ticker := time.NewTicker(1 * time.Minute)
2024-09-06 14:06:32 -04:00
defer ticker.Stop()
archivePool = nostr.NewSimplePool(ctx)
2024-09-06 14:06:32 -04:00
for range ticker.C {
2024-09-06 17:39:39 -04:00
timeout, cancel := context.WithTimeout(ctx, 58*time.Second)
2024-09-06 14:06:32 -04:00
filters := []nostr.Filter{{
Kinds: []int{
nostr.KindArticle,
nostr.KindDeletion,
nostr.KindContactList,
nostr.KindEncryptedDirectMessage,
nostr.KindMuteList,
nostr.KindReaction,
nostr.KindRelayListMetadata,
nostr.KindRepost,
nostr.KindZapRequest,
nostr.KindZap,
nostr.KindTextNote,
},
}}
2024-09-06 17:15:39 -04:00
for ev := range archivePool.SubManyEose(timeout, relays, filters) {
2024-09-06 17:39:39 -04:00
for _, trustedPubkey := range trustNetwork {
2024-09-06 14:06:32 -04:00
if ev.Event.PubKey == trustedPubkey {
if ev.Event.Kind == nostr.KindContactList {
if len(ev.Event.Tags.GetAll([]string{"p"})) > 2000 {
fmt.Println("archiveTrustedNotes: skipping contact list with more than 2000 contacts. NoteID: ", ev.Event.ID)
continue
}
}
2024-09-06 14:06:32 -04:00
relay.AddEvent(ctx, ev.Event)
2024-09-06 17:39:39 -04:00
fmt.Println("archived trusted note: ", ev.Event.ID)
2024-09-06 14:06:32 -04:00
}
2024-09-06 11:16:40 -04:00
}
}
cancel()
2024-09-06 11:16:40 -04:00
}
}