forked from nbd-wtf/go-nostr
-
Notifications
You must be signed in to change notification settings - Fork 1
/
relay_test.go
231 lines (211 loc) · 5.69 KB
/
relay_test.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
package nostr
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"golang.org/x/net/websocket"
)
func TestPublish(t *testing.T) {
// test note to be sent over websocket
priv, pub := makeKeyPair(t)
textNote := Event{
Kind: 1,
Content: "hello",
CreatedAt: time.Unix(1672068534, 0), // random fixed timestamp
Tags: Tags{[]string{"foo", "bar"}},
PubKey: pub,
}
if err := textNote.Sign(priv); err != nil {
t.Fatalf("textNote.Sign: %v", err)
}
// fake relay server
var mu sync.Mutex // guards published to satisfy go test -race
var published bool
ws := newWebsocketServer(func(conn *websocket.Conn) {
mu.Lock()
published = true
mu.Unlock()
// verify the client sent exactly the textNote
var raw []json.RawMessage
if err := websocket.JSON.Receive(conn, &raw); err != nil {
t.Errorf("websocket.JSON.Receive: %v", err)
}
event := parseEventMessage(t, raw)
if !bytes.Equal(event.Serialize(), textNote.Serialize()) {
t.Errorf("received event:\n%+v\nwant:\n%+v", event, textNote)
}
// send back an ok nip-20 command result
res := []any{"OK", textNote.ID, true, ""}
if err := websocket.JSON.Send(conn, res); err != nil {
t.Errorf("websocket.JSON.Send: %v", err)
}
})
defer ws.Close()
// connect a client and send the text note
rl := mustRelayConnect(ws.URL)
want := map[Status]bool{
PublishStatusSent: true,
PublishStatusSucceeded: true,
}
testPublishStatus(t, rl.Publish(textNote), want)
if !published {
t.Errorf("fake relay server saw no event")
}
}
func TestPublishBlocked(t *testing.T) {
// test note to be sent over websocket
textNote := Event{Kind: 1, Content: "hello"}
textNote.ID = textNote.GetID()
// fake relay server
ws := newWebsocketServer(func(conn *websocket.Conn) {
// discard received message; not interested
var raw []json.RawMessage
if err := websocket.JSON.Receive(conn, &raw); err != nil {
t.Errorf("websocket.JSON.Receive: %v", err)
}
// send back a not ok nip-20 command result
res := []any{"OK", textNote.ID, false, "blocked"}
websocket.JSON.Send(conn, res)
})
defer ws.Close()
// connect a client and send a text note
rl := mustRelayConnect(ws.URL)
want := map[Status]bool{
PublishStatusSent: true,
PublishStatusFailed: true,
}
testPublishStatus(t, rl.Publish(textNote), want)
}
func TestConnectContext(t *testing.T) {
// fake relay server
var mu sync.Mutex // guards connected to satisfy go test -race
var connected bool
ws := newWebsocketServer(func(conn *websocket.Conn) {
mu.Lock()
connected = true
mu.Unlock()
io.ReadAll(conn) // discard all input
})
defer ws.Close()
// relay client
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
r, err := RelayConnectContext(ctx, ws.URL)
if err != nil {
t.Fatalf("RelayConnectContext: %v", err)
}
defer r.Close()
mu.Lock()
defer mu.Unlock()
if !connected {
t.Error("fake relay server saw no client connect")
}
}
func TestConnectContextCanceled(t *testing.T) {
// fake relay server
ws := newWebsocketServer(func(conn *websocket.Conn) {
io.ReadAll(conn) // discard all input
})
defer ws.Close()
// relay client
ctx, cancel := context.WithCancel(context.Background())
cancel() // make ctx expired
_, err := RelayConnectContext(ctx, ws.URL)
if !errors.Is(err, context.Canceled) {
t.Errorf("RelayConnectContext returned %v error; want context.Canceled", err)
}
}
func newWebsocketServer(handler func(*websocket.Conn)) *httptest.Server {
return httptest.NewServer(&websocket.Server{
Handshake: anyOriginHandshake,
Handler: handler,
})
}
// anyOriginHandshake is an alternative to default in golang.org/x/net/websocket
// which checks for origin. nostr client sends no origin and it makes no difference
// for the tests here anyway.
var anyOriginHandshake = func(conf *websocket.Config, r *http.Request) error {
return nil
}
func makeKeyPair(t *testing.T) (priv, pub string) {
t.Helper()
privkey := GeneratePrivateKey()
pubkey, err := GetPublicKey(privkey)
if err != nil {
t.Fatalf("GetPublicKey(%q): %v", privkey, err)
}
return privkey, pubkey
}
func mustRelayConnect(url string) *Relay {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
rl, err := RelayConnectContext(ctx, url)
if err != nil {
panic(err.Error())
}
return rl
}
func parseEventMessage(t *testing.T, raw []json.RawMessage) Event {
t.Helper()
if len(raw) < 2 {
t.Fatalf("len(raw) = %d; want at least 2", len(raw))
}
var typ string
json.Unmarshal(raw[0], &typ)
if typ != "EVENT" {
t.Errorf("typ = %q; want EVENT", typ)
}
var event Event
if err := json.Unmarshal(raw[1], &event); err != nil {
t.Errorf("json.Unmarshal: %v", err)
}
return event
}
func parseSubscriptionMessage(t *testing.T, raw []json.RawMessage) (subid string, filters []Filter) {
t.Helper()
if len(raw) < 3 {
t.Fatalf("len(raw) = %d; want at least 3", len(raw))
}
var typ string
json.Unmarshal(raw[0], &typ)
if typ != "REQ" {
t.Errorf("typ = %q; want REQ", typ)
}
var id string
if err := json.Unmarshal(raw[1], &id); err != nil {
t.Errorf("json.Unmarshal sub id: %v", err)
}
var ff []Filter
for i, b := range raw[2:] {
var f Filter
if err := json.Unmarshal(b, &f); err != nil {
t.Errorf("json.Unmarshal filter %d: %v", i, err)
}
ff = append(ff, f)
}
return id, ff
}
func testPublishStatus(t *testing.T, ch <-chan Status, want map[Status]bool) {
for stat := range ch {
if !want[stat] {
t.Errorf("client reported %q status", stat)
}
delete(want, stat)
// stop early to speed up tests
if len(want) == 0 {
break
}
}
for stat, missed := range want {
if missed {
t.Errorf("client didn't report %q", stat)
}
}
}