forked from nbd-wtf/nostr-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
relay.js
210 lines (187 loc) · 5.18 KB
/
relay.js
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
/* global WebSocket */
import 'websocket-polyfill'
import {verifySignature, validateEvent} from './event.js'
import {matchFilters} from './filter.js'
export function normalizeRelayURL(url) {
let [host, ...qs] = url.trim().split('?')
if (host.slice(0, 4) === 'http') host = 'ws' + host.slice(4)
if (host.slice(0, 2) !== 'ws') host = 'wss://' + host
if (host.length && host[host.length - 1] === '/') host = host.slice(0, -1)
return [host, ...qs].join('?')
}
export function relayConnect(url, onNotice = () => {}, onError = () => {}) {
url = normalizeRelayURL(url)
var ws, resolveOpen, untilOpen, wasClosed
var openSubs = {}
var isSetToSkipVerification = {}
let attemptNumber = 1
let nextAttemptSeconds = 1
function resetOpenState() {
untilOpen = new Promise(resolve => {
resolveOpen = resolve
})
}
var eventListeners = {}
var eoseListeners = {}
function connect() {
ws = new WebSocket(url)
ws.onopen = () => {
console.log('connected to', url)
resolveOpen()
// restablish old subscriptions
if (wasClosed) {
wasClosed = false
for (let channel in openSubs) {
let filters = openSubs[channel]
let eventCb = eventListeners[channel]
let eoseCb = eoseListeners[channel]
sub({eventCb, filter: filters}, channel, eoseCb)
}
}
}
ws.onerror = err => {
console.log('error connecting to relay', url)
onError(err)
}
ws.onclose = () => {
resetOpenState()
attemptNumber++
nextAttemptSeconds += attemptNumber ** 3
if (nextAttemptSeconds > 14400) {
nextAttemptSeconds = 14400 // 4 hours
}
console.log(
`relay ${url} connection closed. reconnecting in ${nextAttemptSeconds} seconds.`
)
setTimeout(async () => {
try {
connect()
} catch (err) {}
}, nextAttemptSeconds * 1000)
wasClosed = true
}
ws.onmessage = async e => {
var data
try {
data = JSON.parse(e.data)
} catch (err) {
data = e.data
}
if (data.length >= 1) {
switch (data[0]) {
case 'NOTICE':
if (data.length != 2) {
// ignore empty or malformed notice
return
}
console.log(`message from relay ${url}: ${data[1]}`)
onNotice(data[1])
return
case 'EOSE':
if (data.length != 2) {
// ignore malformed EOSE
return
}
console.log(`Channel ${data[1]}: End-of-stored-events`)
if (eoseListeners[data[1]]) {
eoseListeners[data[1]]()
}
return
case 'EVENT':
if (data.length != 3) {
// ignore malformed EVENT
return
}
let channel = data[1]
let event = data[2]
if (validateEvent(event) &&
(isSetToSkipVerification[channel] || verifySignature(event)) &&
eventListeners[channel] &&
matchFilters(openSubs[channel], event)) {
eventListeners[channel](event)
}
return
}
}
}
}
resetOpenState()
try {
connect()
} catch (err) {}
async function trySend(params) {
let msg = JSON.stringify(params)
await untilOpen
ws.send(msg)
}
const sub = (
{cb, filter, beforeSend, skipVerification},
channel = Math.random().toString().slice(2),
eoseCb
) => {
var filters = []
if (Array.isArray(filter)) {
filters = filter
} else {
filters.push(filter)
}
if (beforeSend) {
const beforeSendResult = beforeSend({filter, relay: url, channel})
filters = beforeSendResult.filter
}
trySend(['REQ', channel, ...filters])
eventListeners[channel] = cb
eoseListeners[channel] = eoseCb
openSubs[channel] = filters
isSetToSkipVerification[channel] = skipVerification
const activeCallback = cb
const activeFilters = filters
const activeBeforeSend = beforeSend
return {
sub: ({
cb = activeCallback,
filter = activeFilters,
beforeSend = activeBeforeSend
}) => sub({cb, filter, beforeSend, skipVerification}, channel),
unsub: () => {
delete openSubs[channel]
delete eventListeners[channel]
delete eoseListeners[channel]
delete isSetToSkipVerification[channel]
trySend(['CLOSE', channel])
}
}
}
return {
url,
sub,
async publish(event, statusCallback) {
try {
await trySend(['EVENT', event])
if (statusCallback) {
statusCallback(0)
let {unsub} = sub(
{
cb: () => {
statusCallback(1)
unsub()
clearTimeout(willUnsub)
},
filter: {ids: [event.id]}
},
`monitor-${event.id.slice(0, 5)}`
)
let willUnsub = setTimeout(unsub, 5000)
}
} catch (err) {
if (statusCallback) statusCallback(-1)
}
},
close() {
ws.close()
},
get status() {
return ws.readyState
}
}
}