forked from nbd-wtf/go-nostr
-
Notifications
You must be signed in to change notification settings - Fork 1
/
relay.go
294 lines (249 loc) · 6.69 KB
/
relay.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
package nostr
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
//"log"
"time"
s "github.com/SaveTheRbtz/generic-sync-map-go"
"github.com/gorilla/websocket"
)
type Status int
const (
PublishStatusSent Status = 0
PublishStatusFailed Status = -1
PublishStatusSucceeded Status = 1
)
func (s Status) String() string {
switch s {
case PublishStatusSent:
return "sent"
case PublishStatusFailed:
return "failed"
case PublishStatusSucceeded:
return "success"
}
return "unknown"
}
type Relay struct {
URL string
Connection *Connection
subscriptions s.MapOf[string, *Subscription]
Notices chan string
ConnectionError chan error
statusChans s.MapOf[string, chan Status]
}
// RelayConnect forwards calls to RelayConnectContext with a background context.
func RelayConnect(url string) (*Relay, error) {
return RelayConnectContext(context.Background(), url)
}
// RelayConnectContext creates a new relay client and connects to a canonical
// URL using Relay.ConnectContext, passing ctx as is.
func RelayConnectContext(ctx context.Context, url string) (*Relay, error) {
r := &Relay{URL: NormalizeURL(url)}
err := r.ConnectContext(ctx)
return r, err
}
func (r *Relay) String() string {
return r.URL
}
// Connect calls ConnectContext with a background context.
func (r *Relay) Connect() error {
return r.ConnectContext(context.Background())
}
// ConnectContext tries to establish a websocket connection to r.URL.
// If the context expires before the connection is complete, an error is returned.
// Once successfully connected, context expiration has no effect: call r.Close
// to close the connection.
func (r *Relay) ConnectContext(ctx context.Context) error {
if r.URL == "" {
return fmt.Errorf("invalid relay URL '%s'", r.URL)
}
socket, _, err := websocket.DefaultDialer.DialContext(ctx, r.URL, nil)
if err != nil {
return fmt.Errorf("error opening websocket to '%s': %w", r.URL, err)
}
r.Notices = make(chan string)
r.ConnectionError = make(chan error)
conn := NewConnection(socket)
r.Connection = conn
go func() {
for {
typ, message, err := conn.socket.ReadMessage()
if err != nil {
r.ConnectionError <- err
break
}
if typ == websocket.PingMessage {
conn.WriteMessage(websocket.PongMessage, nil)
continue
}
if typ != websocket.TextMessage || len(message) == 0 || message[0] != '[' {
continue
}
var jsonMessage []json.RawMessage
err = json.Unmarshal(message, &jsonMessage)
if err != nil {
continue
}
if len(jsonMessage) < 2 {
continue
}
var label string
json.Unmarshal(jsonMessage[0], &label)
switch label {
case "NOTICE":
var content string
json.Unmarshal(jsonMessage[1], &content)
r.Notices <- content
case "EVENT":
if len(jsonMessage) < 3 {
continue
}
var channel string
json.Unmarshal(jsonMessage[1], &channel)
if subscription, ok := r.subscriptions.Load(channel); ok {
var event Event
json.Unmarshal(jsonMessage[2], &event)
//we are dropping valid sigs, allow invalid and figure this out later
if _, err := event.CheckSignature(); err != nil {
//fmt.Printf("\nfailed sig\n%s\n", jsonMessage[2])
continue
}
// check signature of all received events, ignore invalid
// ok, err := event.CheckSignature()
// if !ok {
// errmsg := ""
// if err != nil {
// errmsg = err.Error()
// }
// log.Printf("bad signature: %s", errmsg)
// continue
// }
// check if the event matches the desired filter, ignore otherwise
if !subscription.Filters.Match(&event) {
continue
}
if !subscription.stopped {
subscription.Events <- event
}
}
case "EOSE":
if len(jsonMessage) < 2 {
continue
}
var channel string
json.Unmarshal(jsonMessage[1], &channel)
if subscription, ok := r.subscriptions.Load(channel); ok {
subscription.emitEose.Do(func() {
subscription.EndOfStoredEvents <- struct{}{}
})
}
case "OK":
if len(jsonMessage) < 3 {
continue
}
var (
eventId string
ok bool
)
json.Unmarshal(jsonMessage[1], &eventId)
json.Unmarshal(jsonMessage[2], &ok)
if statusChan, exist := r.statusChans.Load(eventId); exist {
if ok {
//statusChan <- PublishStatusSucceeded
} else {
statusChan <- PublishStatusFailed
}
}
}
}
}()
return nil
}
func (r *Relay) Publish(event Event) chan Status {
statusChan := make(chan Status, 4)
go func() {
// we keep track of this so the OK message can be used to close it
r.statusChans.Store(event.ID, statusChan)
defer r.statusChans.Delete(event.ID)
err := r.Connection.WriteJSON([]interface{}{"EVENT", event})
if err != nil {
statusChan <- PublishStatusFailed
close(statusChan)
return
}
statusChan <- PublishStatusSent
// TODO: there's no reason to sub if the relay supports nip-20 (command results).
// in fact, subscribing here with nip20-enabled relays makes it send PublishStatusSucceded
// twice: once here, and the other on "OK" command result.
sub := r.Subscribe(Filters{Filter{IDs: []string{event.ID}}})
for {
select {
case receivedEvent := <-sub.Events:
if receivedEvent.ID == event.ID {
statusChan <- PublishStatusSucceeded
close(statusChan)
break
} else {
continue
}
case <-time.After(5 * time.Second):
close(statusChan)
break
}
break
}
}()
return statusChan
}
func (r *Relay) MustPublish(event Event) {
go func() {
r.Connection.WriteJSON([]interface{}{"EVENT", event})
}()
}
func (r *Relay) Subscribe(filters Filters) *Subscription {
if r.Connection == nil {
panic(fmt.Errorf("must call .Connect() first before calling .Subscribe()"))
}
sub := r.PrepareSubscription()
sub.Filters = filters
sub.Fire()
return sub
}
func (r *Relay) QuerySync(filter Filter, timeout time.Duration) []Event {
sub := r.Subscribe(Filters{filter})
var events []Event
for {
select {
case evt := <-sub.Events:
events = append(events, evt)
case <-sub.EndOfStoredEvents:
return events
case <-time.After(timeout):
return events
}
}
}
func (r *Relay) PrepareSubscription() *Subscription {
random := make([]byte, 7)
rand.Read(random)
id := hex.EncodeToString(random)
return r.prepareSubscription(id)
}
func (r *Relay) prepareSubscription(id string) *Subscription {
sub := &Subscription{
Relay: r,
conn: r.Connection,
id: id,
Events: make(chan Event),
EndOfStoredEvents: make(chan struct{}, 1),
}
r.subscriptions.Store(sub.id, sub)
return sub
}
func (r *Relay) Close() error {
return r.Connection.Close()
}