forked from fiatjaf/njump
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnostr.go
362 lines (310 loc) · 9.03 KB
/
nostr.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
package main
import (
"context"
"fmt"
"slices"
"sync"
"time"
"github.com/fiatjaf/eventstore/lmdb"
"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/nip19"
"github.com/nbd-wtf/go-nostr/sdk"
cache_memory "github.com/nbd-wtf/go-nostr/sdk/cache/memory"
)
type RelayConfig struct {
Everything []string `json:"everything"`
Profiles []string `json:"profiles"`
JustIds []string `json:"justIds"`
}
var (
sys *sdk.System
serial int
relayConfig = RelayConfig{
Everything: nil, // use the defaults from nostr-sdk
Profiles: nil, // use the defaults from nostr-sdk
JustIds: []string{
"wss://cache2.primal.net/v1",
"wss://relay.noswhere.com",
"wss://relay.damus.io",
},
}
defaultTrustedPubKeys = []string{
"7bdef7be22dd8e59f4600e044aa53a1cf975a9dc7d27df5833bc77db784a5805", // dtonon
"3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d", // fiatjaf
"97c70a44366a6535c145b333f973ea86dfdc2d7a99da618c40c64705ad98e322", // hodlbod
"ee11a5dff40c19a555f41fe42b48f00e618c91225622ae37b6c2bb67b76c4e49", // Michael Dilger
}
)
type CachedEvent struct {
Event *nostr.Event `json:"e"`
Relays []string `json:"r"`
}
func initSystem() func() {
db := &lmdb.LMDBBackend{
Path: s.EventStorePath,
}
db.Init()
sys = sdk.NewSystem(
sdk.WithMetadataCache(cache_memory.New32[sdk.ProfileMetadata](10000)),
sdk.WithRelayListCache(cache_memory.New32[sdk.RelayList](10000)),
sdk.WithStore(db),
)
return db.Close
}
func getEvent(ctx context.Context, code string) (*nostr.Event, []string, error) {
// this is for deciding what relays will go on nevent and nprofile later
priorityRelays := make(map[string]int)
prefix, data, err := nip19.Decode(code)
if err != nil {
return nil, nil, fmt.Errorf("failed to decode %w", err)
}
author := ""
authorRelaysPosition := 0
var filter nostr.Filter
relays := make([]string, 0, 10)
switch v := data.(type) {
case nostr.EventPointer:
author = v.Author
filter.IDs = []string{v.ID}
relays = append(relays, v.Relays...)
relays = append(relays, relayConfig.JustIds...)
authorRelaysPosition = len(v.Relays) // ensure author relays are checked after hinted relays
for _, r := range v.Relays {
priorityRelays[r] = 2
}
case nostr.EntityPointer:
author = v.PublicKey
filter.Authors = []string{v.PublicKey}
filter.Tags = nostr.TagMap{
"d": []string{v.Identifier},
}
if v.Kind != 0 {
filter.Kinds = append(filter.Kinds, v.Kind)
}
relays = append(relays, v.Relays...)
authorRelaysPosition = len(v.Relays) // ensure author relays are checked after hinted relays
case string:
if prefix == "note" {
filter.IDs = []string{v}
relays = append(relays, relayConfig.JustIds...)
}
}
// try to fetch in our internal eventstore first
if res, _ := sys.StoreRelay.QuerySync(ctx, filter); len(res) != 0 {
evt := res[0]
// keep this event in cache for a while more
// unless it's a metadata event
// (people complaining about njump keeping their metadata will try to load their metadata all the time)
if evt.Kind != 0 {
scheduleEventExpiration(evt.ID, time.Hour*24*7)
}
return evt, getRelaysForEvent(evt.ID), nil
}
if author != "" {
// fetch relays for author
authorRelays := sys.FetchOutboxRelays(ctx, author, 3)
relays = slices.Insert(relays, authorRelaysPosition, authorRelays...)
for _, r := range authorRelays {
priorityRelays[r] = 1
}
}
for len(relays) < 5 {
relays = append(relays, getRandomRelay())
}
relays = unique(relays)
var result *nostr.Event
var successRelays []string = nil
{
// actually fetch the event here
subManyCtx, cancel := context.WithTimeout(ctx, time.Second*8)
defer cancel()
// keep track of where we have actually found the event so we can show that
successRelays = make([]string, 0, len(relays))
countdown := 7.5
go func() {
for {
time.Sleep(500 * time.Millisecond)
if countdown <= 0 {
cancel()
break
}
countdown -= 0.5
}
}()
fetchProfileOnce := sync.Once{}
for ie := range sys.Pool.SubManyEoseNonUnique(
subManyCtx,
relays,
nostr.Filters{filter},
nostr.WithLabel("fetching "+prefix),
) {
fetchProfileOnce.Do(func() {
go sys.FetchProfileMetadata(ctx, ie.PubKey)
})
successRelays = append(successRelays, ie.Relay.URL)
if result == nil || ie.CreatedAt > result.CreatedAt {
result = ie.Event
}
countdown = min(countdown, 1)
}
}
if result == nil {
log.Debug().Str("code", code).Msg("couldn't find")
return nil, nil, fmt.Errorf("couldn't find this %s, did you include relay or author hints in it?", prefix)
}
// save stuff in cache and in internal store
sys.StoreRelay.Publish(ctx, *result)
// save relays if we got them
allRelays := attachRelaysToEvent(result.ID, successRelays...)
// put priority relays first so they get used in nevent and nprofile
slices.SortFunc(allRelays, func(a, b string) int {
vpa, _ := priorityRelays[a]
vpb, _ := priorityRelays[b]
return vpb - vpa
})
// keep track of what we have to delete later
scheduleEventExpiration(result.ID, time.Hour*24*7)
return result, allRelays, nil
}
func authorLastNotes(ctx context.Context, pubkey string, isSitemap bool) []EnhancedEvent {
var limit int
var store bool
var useLocalStore bool
if isSitemap {
limit = 50000
store = false
useLocalStore = false
} else {
limit = 100
store = true
useLocalStore = true
go sys.FetchProfileMetadata(ctx, pubkey) // fetch this before so the cache is filled for later
}
filter := nostr.Filter{
Kinds: []int{nostr.KindTextNote},
Authors: []string{pubkey},
Limit: limit,
}
lastNotes := make([]EnhancedEvent, 0, filter.Limit)
// fetch from local store if available
if useLocalStore {
ch, err := sys.Store.QueryEvents(ctx, filter)
if err == nil {
for evt := range ch {
lastNotes = append(lastNotes, NewEnhancedEvent(ctx, evt))
if store {
sys.Store.SaveEvent(ctx, evt)
scheduleEventExpiration(evt.ID, time.Hour*24)
}
}
}
}
if len(lastNotes) < 5 {
// if we didn't get enough notes (or if we didn't even query the local store), wait for the external relays
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
relays := sys.FetchOutboxRelays(ctx, pubkey, 3)
for len(relays) < 3 {
relays = unique(append(relays, getRandomRelay()))
}
ch := sys.Pool.SubManyEose(ctx, relays, nostr.Filters{filter}, nostr.WithLabel("authorlast"))
out:
for {
select {
case ie, more := <-ch:
if !more {
break out
}
ee := NewEnhancedEvent(ctx, ie.Event)
ee.relays = unique(append([]string{ie.Relay.URL}, getRelaysForEvent(ie.Event.ID)...))
lastNotes = append(lastNotes, ee)
if store {
sys.Store.SaveEvent(ctx, ie.Event)
attachRelaysToEvent(ie.Event.ID, ie.Relay.URL)
scheduleEventExpiration(ie.Event.ID, time.Hour*24)
}
case <-ctx.Done():
break out
}
}
}
// sort before returning
slices.SortFunc(lastNotes, func(a, b EnhancedEvent) int { return int(b.CreatedAt - a.CreatedAt) })
return lastNotes
}
func relayLastNotes(ctx context.Context, relayUrl string, isSitemap bool) []*nostr.Event {
key := ""
limit := 1000
if isSitemap {
key = "rlns:" + nostr.NormalizeURL(relayUrl)
limit = 5000
} else {
key = "rln:" + nostr.NormalizeURL(relayUrl)
}
lastNotes := make([]*nostr.Event, 0, limit)
if ok := cache.GetJSON(key, &lastNotes); ok {
return lastNotes
}
ctx, cancel := context.WithTimeout(ctx, time.Second*4)
defer cancel()
if relay, err := sys.Pool.EnsureRelay(relayUrl); err == nil {
lastNotes, _ = relay.QuerySync(ctx, nostr.Filter{
Kinds: []int{1},
Limit: limit,
})
}
slices.SortFunc(lastNotes, func(a, b *nostr.Event) int { return int(b.CreatedAt - a.CreatedAt) })
if len(lastNotes) > 0 {
cache.SetJSONWithTTL(key, lastNotes, time.Hour*24)
}
return lastNotes
}
func contactsForPubkey(ctx context.Context, pubkey string) []string {
pubkeyContacts := make([]string, 0, 300)
relays := make([]string, 0, 12)
if ok := cache.GetJSON("cc:"+pubkey, &pubkeyContacts); !ok {
log.Debug().Msgf("searching contacts for %s", pubkey)
ctx, cancel := context.WithTimeout(ctx, time.Second*3)
pubkeyRelays := sys.FetchOutboxRelays(ctx, pubkey, 3)
relays = append(relays, pubkeyRelays...)
relays = append(relays, sys.MetadataRelays...)
ch := sys.Pool.SubManyEose(
ctx,
relays,
nostr.Filters{{Kinds: []int{3}, Authors: []string{pubkey}, Limit: 2}},
nostr.WithLabel("contacts"),
)
for {
select {
case evt, more := <-ch:
if !more {
goto end
}
for _, tag := range evt.Tags {
if tag[0] == "p" {
pubkeyContacts = append(pubkeyContacts, tag[1])
}
}
case <-ctx.Done():
goto end
}
}
end:
cancel()
if len(pubkeyContacts) > 0 {
cache.SetJSONWithTTL("cc:"+pubkey, pubkeyContacts, time.Hour*6)
}
}
return unique(pubkeyContacts)
}
func relaysPretty(ctx context.Context, pubkey string) []string {
s := make([]string, 0, 3)
for _, url := range sys.FetchOutboxRelays(ctx, pubkey, 3) {
trimmed := trimProtocolAndEndingSlash(url)
if slices.Contains(s, trimmed) {
continue
}
s = append(s, trimmed)
}
return s
}