forked from nbd-wtf/go-nostr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
relaypool.go
259 lines (214 loc) · 5.54 KB
/
relaypool.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
package nostr
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log"
"time"
"github.com/fiatjaf/bip340"
"github.com/gorilla/websocket"
)
const (
PublishStatusSent = 0
PublishStatusFailed = -1
PublishStatusSucceeded = 1
)
type PublishStatus struct {
Relay string
Status int
}
type RelayPool struct {
SecretKey *string
Relays map[string]RelayPoolPolicy
websockets map[string]*Connection
subscriptions map[string]*Subscription
Notices chan *NoticeMessage
}
type RelayPoolPolicy interface {
ShouldRead(EventFilters) bool
ShouldWrite(*Event) bool
}
type SimplePolicy struct {
Read bool
Write bool
}
func (s SimplePolicy) ShouldRead(_ EventFilters) bool {
return s.Read
}
func (s SimplePolicy) ShouldWrite(_ *Event) bool {
return s.Write
}
type NoticeMessage struct {
Message string
Relay string
}
// New creates a new RelayPool with no relays in it
func NewRelayPool() *RelayPool {
return &RelayPool{
Relays: make(map[string]RelayPoolPolicy),
websockets: make(map[string]*Connection),
subscriptions: make(map[string]*Subscription),
Notices: make(chan *NoticeMessage),
}
}
// Add adds a new relay to the pool, if policy is nil, it will be a simple
// read+write policy.
func (r *RelayPool) Add(url string, policy RelayPoolPolicy) error {
if policy == nil {
policy = SimplePolicy{Read: true, Write: true}
}
nm := NormalizeURL(url)
if nm == "" {
return fmt.Errorf("invalid relay URL '%s'", url)
}
socket, _, err := websocket.DefaultDialer.Dial(NormalizeURL(url), nil)
if err != nil {
return fmt.Errorf("error opening websocket to '%s': %w", nm, err)
}
conn := NewConnection(socket)
r.Relays[nm] = policy
r.websockets[nm] = conn
for _, sub := range r.subscriptions {
sub.addRelay(nm, conn)
}
go func() {
for {
typ, message, err := conn.socket.ReadMessage()
if err != nil {
panic("read error: " + err.Error())
return
}
if typ == websocket.PingMessage {
conn.WriteMessage(websocket.PongMessage, nil)
}
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 <- &NoticeMessage{
Relay: nm,
Message: content,
}
case "EVENT":
if len(jsonMessage) < 3 {
continue
}
var channel string
json.Unmarshal(jsonMessage[1], &channel)
if subscription, ok := r.subscriptions[channel]; ok {
var event Event
json.Unmarshal(jsonMessage[2], &event)
// check signature of all received events, ignore invalid
ok, _ := event.CheckSignature()
if !ok {
continue
}
// check if the event matches the desired filter, ignore otherwise
if !subscription.filters.Match(&event) {
continue
}
subscription.Events <- EventMessage{
Relay: nm,
Event: event,
}
}
}
}
}()
return nil
}
// Remove removes a relay from the pool.
func (r *RelayPool) Remove(url string) {
nm := NormalizeURL(url)
for _, sub := range r.subscriptions {
sub.removeRelay(nm)
}
if conn, ok := r.websockets[nm]; ok {
conn.Close()
}
delete(r.Relays, nm)
delete(r.websockets, nm)
}
func (r *RelayPool) Sub(filters EventFilters) *Subscription {
random := make([]byte, 7)
rand.Read(random)
subscription := Subscription{filters: filters}
subscription.channel = hex.EncodeToString(random)
subscription.relays = make(map[string]*Connection)
for relay, policy := range r.Relays {
if policy.ShouldRead(filters) {
ws := r.websockets[relay]
subscription.relays[relay] = ws
}
}
subscription.Events = make(chan EventMessage)
subscription.UniqueEvents = make(chan Event)
r.subscriptions[subscription.channel] = &subscription
subscription.Sub()
return &subscription
}
func (r *RelayPool) PublishEvent(evt *Event) (*Event, chan PublishStatus, error) {
status := make(chan PublishStatus, 1)
if r.SecretKey == nil && (evt.PubKey == "" || evt.Sig == "") {
return nil, status, errors.New("PublishEvent needs either a signed event to publish or to have been configured with a .SecretKey.")
}
if evt.PubKey == "" {
secretKeyN, err := bip340.ParsePrivateKey(*r.SecretKey)
if err != nil {
return nil, status, fmt.Errorf("The pool's global SecretKey is invalid: %w", err)
}
evt.PubKey = fmt.Sprintf("%x", bip340.GetPublicKey(secretKeyN))
}
if evt.Sig == "" {
err := evt.Sign(*r.SecretKey)
if err != nil {
return nil, status, fmt.Errorf("Error signing event: %w", err)
}
}
for relay, conn := range r.websockets {
if !r.Relays[relay].ShouldWrite(evt) {
continue
}
go func(relay string, conn *Connection) {
err := conn.WriteJSON([]interface{}{"EVENT", evt})
if err != nil {
log.Printf("error sending event to '%s': %s", relay, err.Error())
status <- PublishStatus{relay, PublishStatusFailed}
}
status <- PublishStatus{relay, PublishStatusSent}
subscription := r.Sub(EventFilters{EventFilter{IDs: []string{evt.ID}}})
for {
select {
case event := <-subscription.UniqueEvents:
if event.ID == evt.ID {
status <- PublishStatus{relay, PublishStatusSucceeded}
break
} else {
continue
}
case <-time.After(5 * time.Second):
break
}
break
}
subscription.Unsub()
close(status)
}(relay, conn)
}
return evt, status, nil
}