-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
412 lines (349 loc) · 9.8 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package main
import (
"context"
"embed"
"fmt"
"html/template"
"io"
"io/fs"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
"github.com/fiatjaf/eventstore"
"github.com/fiatjaf/khatru"
"github.com/fiatjaf/khatru/policies"
"github.com/joho/godotenv"
"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/nip10"
"github.com/nbd-wtf/go-nostr/nip13"
)
//go:embed template/index.html
var indexHTML string
//go:embed template/assets
var assets embed.FS
var (
version string
)
type Config struct {
OwnerPubkey string
RelayName string
RelayDescription string
DBPath string
RelayURL string
RelayPort string
RefreshInterval int
MinFollowers int
FetchSync bool
RelayContact string
RelayIcon string
PowWhitelist int
PowDMWhitelist int
}
var pool *nostr.SimplePool
var wdb nostr.RelayStore
var rootNotesList *RootNotes
var relays []string
var config Config
var trustNetwork []string
var oneHopNetwork []string
var trustNetworkMap map[string]bool
var pubkeyFollowerCount = make(map[string]int)
var trustedNotes uint64
var untrustedNotes uint64
var relay *khatru.Relay
func main() {
nostr.InfoLogger = log.New(io.Discard, "", 0)
magenta := "\033[91m"
gray := "\033[90m"
reset := "\033[0m"
art := magenta + `
____ _ _ _
/ ___| |__ _ __ ___ _ __ (_) ___| | ___
| | | '_ \| '__/ _ \| '_ \| |/ __| |/ _ \
| |___| | | | | | (_) | | | | | (__| | __/
\____|_| |_|_| \___/|_| |_|_|\___|_|\___|` + gray + `
powered by Khatru
` + reset
fmt.Println(art)
log.Println("🚀 Booting up Chronicle relay")
relay := khatru.NewRelay()
ctx := context.Background()
pool = nostr.NewSimplePool(ctx)
config = LoadConfig()
relay.Info.Name = config.RelayName
relay.Info.PubKey = config.OwnerPubkey
relay.Info.Icon = config.RelayIcon
relay.Info.Contact = config.RelayContact
relay.Info.Description = config.RelayDescription
relay.Info.Software = "https://github.com/dtonon/chronicle"
relay.Info.Version = version
appendPubkey(config.OwnerPubkey)
db := getDB()
if err := db.Init(); err != nil {
panic(err)
}
wdb = eventstore.RelayWrapper{Store: &db}
rootNotesList = NewRootNotes("db/root_notes")
if err := rootNotesList.LoadFromFile(); err != nil {
fmt.Println("Error loading strings:", err)
return
} else {
log.Println("🗣️ Monitoring", rootNotesList.Size(), "threads")
}
relay.RejectEvent = append(relay.RejectEvent,
policies.RejectEventsWithBase64Media,
policies.EventIPRateLimiter(5, time.Minute*1, 30),
)
relay.RejectFilter = append(relay.RejectFilter,
policies.NoEmptyFilters,
policies.NoComplexFilters,
)
relay.RejectConnection = append(relay.RejectConnection,
policies.ConnectionRateLimiter(10, time.Minute*2, 30),
)
relay.StoreEvent = append(relay.StoreEvent, db.SaveEvent)
relay.QueryEvents = append(relay.QueryEvents, db.QueryEvents)
relay.DeleteEvent = append(relay.DeleteEvent, db.DeleteEvent)
relay.RejectEvent = append(relay.RejectEvent, func(ctx context.Context, event *nostr.Event) (bool, string) {
if acceptedEvent(*event) {
addEventToRootList(*event)
go fetchQuotedEvents(*event)
go fetchConversation(*event)
return false, ""
}
return true, "event not allowed"
})
// WoT and archiving procedures
var wg sync.WaitGroup
wg.Add(1) // We expect one goroutine to finish
interval := time.Duration(config.RefreshInterval) * time.Hour
ticker := time.NewTicker(interval)
defer ticker.Stop()
go func() {
refreshProfiles(ctx)
refreshTrustNetwork(ctx, relay)
wg.Done()
for {
if config.FetchSync {
archiveTrustedNotes(ctx, relay)
}
<-ticker.C // Wait for the ticker to tick
refreshProfiles(ctx)
refreshTrustNetwork(ctx, relay)
}
}()
// Wait for the first execution to complete
wg.Wait()
mux := relay.Router()
serverRoot, fsErr := fs.Sub(assets, "template/assets")
if fsErr != nil {
log.Fatal(fsErr)
}
mux.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.FS(serverRoot))))
mux.Handle("/favicon.ico", http.FileServer(http.FS(serverRoot)))
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.New("index").Parse(indexHTML))
data := struct {
RelayName string
RelayDescription string
RelayURL string
RelayPort string
OwnerPubkey string
}{
RelayName: config.RelayName,
RelayDescription: config.RelayDescription,
RelayURL: config.RelayURL,
RelayPort: config.RelayPort,
OwnerPubkey: config.OwnerPubkey,
}
err := tmpl.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
log.Println("🎉 Relay running on port", config.RelayPort)
err := http.ListenAndServe(":"+config.RelayPort, relay)
if err != nil {
log.Fatal(err)
}
}
func LoadConfig() Config {
godotenv.Load(".env")
if os.Getenv("REFRESH_INTERVAL") == "" {
os.Setenv("REFRESH_INTERVAL", "3")
}
refreshInterval, _ := strconv.Atoi(os.Getenv("REFRESH_INTERVAL"))
log.Println("📝 Set refresh interval to", refreshInterval, "hours")
if os.Getenv("MIN_FOLLOWERS") == "" {
os.Setenv("MIN_FOLLOWERS", "1")
}
if os.Getenv("FETCH_SYNC") == "" {
os.Setenv("FETCH_SYNC", "TRUE")
}
if os.Getenv("POW_WHITELIST") == "" {
os.Setenv("POW_WHITELIST", "999")
}
if os.Getenv("POW_DM_WHITELIST") == "" {
os.Setenv("POW_DM_WHITELIST", "999")
}
minFollowers, _ := strconv.Atoi(os.Getenv("MIN_FOLLOWERS"))
PowWhitelist, _ := strconv.Atoi(os.Getenv("POW_WHITELIST"))
PowDMWhitelist, _ := strconv.Atoi(os.Getenv("POW_DM_WHITELIST"))
config := Config{
OwnerPubkey: getEnv("OWNER_PUBKEY"),
RelayName: getEnv("RELAY_NAME"),
RelayDescription: getEnv("RELAY_DESCRIPTION"),
RelayContact: getEnv("RELAY_CONTACT"),
RelayIcon: getEnv("RELAY_ICON"),
DBPath: getEnv("DB_PATH"),
RelayURL: getEnv("RELAY_URL"),
RelayPort: getEnv("RELAY_PORT"),
RefreshInterval: refreshInterval,
MinFollowers: minFollowers,
FetchSync: getEnv("FETCH_SYNC") == "TRUE",
PowWhitelist: PowWhitelist,
PowDMWhitelist: PowDMWhitelist,
}
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 acceptedEvent(event nostr.Event) bool {
if event.PubKey == config.OwnerPubkey {
return true
} else if event.Kind == nostr.KindGiftWrap {
for _, tag := range event.Tags.GetAll([]string{"p"}) {
if tag[1] == config.OwnerPubkey {
return (belongsToWotNetwork(event) || nip13.Difficulty(event.ID) >= config.PowDMWhitelist)
}
}
return false
} else if belongsToValidThread(event) &&
(belongsToWotNetwork(event) || nip13.Difficulty(event.ID) >= config.PowWhitelist) {
return true
}
return false
}
func fetchConversation(event nostr.Event) {
rootReference := nip10.GetThreadRoot(event.Tags)
if rootReference == nil || // It's not a reply
rootNotesList.Include(rootReference.Value()) { // It's archived
return // We don't need the full conversation
}
ctx := context.Background()
timeout, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
eventID := rootReference.Value()
eventRelay := rootReference.Relay()
go func() {
filters := []nostr.Filter{
{
IDs: []string{eventID},
},
{
Kinds: []int{
nostr.KindArticle,
nostr.KindDeletion,
nostr.KindReaction,
nostr.KindZapRequest,
nostr.KindZap,
nostr.KindTextNote,
},
Tags: nostr.TagMap{"e": []string{eventID}},
},
}
for ev := range pool.SubMany(timeout, append([]string{eventRelay}, seedRelays...), filters) {
wdb.Publish(ctx, *ev.Event)
go fetchQuotedEvents(*ev.Event)
}
}()
<-timeout.Done()
}
func fetchQuotedEvents(event nostr.Event) {
var quoteIDs []string
var quoteRelays []string
for _, tag := range event.Tags.GetAll([]string{"q", ""}) {
quoteIDs = append(quoteIDs, tag[1])
if len(tag) >= 3 && tag[2] != "" {
quoteRelays = append(quoteRelays, tag[2])
}
}
if len(quoteIDs) == 0 { // No quoted events found
return
}
ctx := context.Background()
timeout, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
go func() {
filters := []nostr.Filter{
{
IDs: quoteIDs,
},
{
Kinds: []int{
nostr.KindDeletion,
nostr.KindReaction,
nostr.KindZapRequest,
nostr.KindZap,
},
Tags: nostr.TagMap{"e": quoteIDs},
},
}
for ev := range pool.SubManyEose(timeout, append(quoteRelays, seedRelays...), filters) {
wdb.Publish(ctx, *ev.Event)
}
}()
<-timeout.Done()
}
func belongsToValidThread(event nostr.Event) bool {
eReference := nip10.GetThreadRoot(event.Tags)
if eReference == nil {
// We already accept root notes by owner
return false
}
if event.Kind == nostr.KindTextNote ||
event.Kind == nostr.KindArticle {
rootCheck := rootNotesList.Include(eReference.Value())
return rootCheck
}
// The event refers to a note in the thread
if event.Kind == nostr.KindDeletion ||
event.Kind == nostr.KindReaction ||
event.Kind == nostr.KindZapRequest ||
event.Kind == nostr.KindZap {
ctx := context.Background()
_, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
filter := nostr.Filter{
IDs: []string{eReference.Value()},
}
eventChan, _ := wdb.QueryEvents(ctx, filter)
for range eventChan {
return true
}
}
return false
}
func addEventToRootList(event nostr.Event) {
// Add only notes and articles to the root list
if event.Kind != nostr.KindTextNote &&
event.Kind != nostr.KindArticle {
return
}
rootReference := nip10.GetThreadRoot(event.Tags)
var rootReferenceValue string
if rootReference == nil { // Is a root post
rootReferenceValue = event.ID
} else { // Is a reply
rootReferenceValue = rootReference.Value()
}
rootNotesList.Add(rootReferenceValue)
}