Repository navigation
Expand file tree
/
Copy pathrelay.rs
More file actions
356 lines (307 loc) · 12.5 KB
/
Copy pathrelay.rs
File metadata and controls
356 lines (307 loc) · 12.5 KB
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
// These options should cover all the cases of needing to choose a set of relays:
//
// Relay::choose_relay_urls(Relay::READ, |_| true)?; // all ours
// Relay::choose_relay_urls(Relay::WRITE, |_| true)?; // all ours
// Relay::choose_relay_urls(Relay::DM, |_| true)?; // all ours
// relay::get_some_pubkey_outboxes(pubkey)? // for subscribing to theirs
// relay::get_all_pubkey_outboxes(pubkey)? // informational
// relay::get_all_pubkey_inboxes(pubkey)? // for replying to them
// relay::get_dm_relays(pubkey)? // for DMs to them
// relay::get_best_relays_with_score(pubkey, usage, score_factors) // for relay picker, and internal
// relay::recommended_relay_hint(reply_to_id)? // for a hint
// relay::relays_for_seeking_replies(&event)? // to find replies
// relay::relays_to_post_to(&event)? // where to post
// future: get_all_pubkey_outboxes_for_batch_search(pubkey)? // for seeker exhaustive search
/// Relay type, aliased to the latest version
pub type Relay = crate::storage::types::Relay3;
pub use crate::storage::types::ScoreFactors;
use crate::error::{Error, ErrorKind};
use crate::person_relay::PersonRelay;
use crate::GLOBALS;
use nostr_types::{Event, EventKind, Id, PublicKey, RelayUrl, RelayUsage, Unixtime};
// Get `num_relays_per_prson` outboxes to subscribe to their events
pub fn get_some_pubkey_outboxes(pubkey: PublicKey) -> Result<Vec<RelayUrl>, Error> {
let num = GLOBALS.db().read_setting_num_relays_per_person() as usize;
let relays =
get_best_relays_with_score(pubkey, RelayUsage::Outbox, ScoreFactors::FULLY_ADJUSTED)?
.iter()
.take(num)
.map(|(url, _score)| url.to_owned())
.collect();
Ok(relays)
}
// Get all person outboxes
pub fn get_all_pubkey_outboxes(pubkey: PublicKey) -> Result<Vec<RelayUrl>, Error> {
// Why 0.125?
// if declared they will get an association score of at least 1.0
// by default based on relay rank, they will get a relay score of 0.33333
// modified by success rate, and 50% success rate will give 75% of this number, which is 0.25
// plus-connected cuts it in half if not connected, so 0.125, and we want to include all
// declared relays even that aren't connected down to 50% success rate.
let relays =
get_best_relays_with_score(pubkey, RelayUsage::Outbox, ScoreFactors::FULLY_ADJUSTED)?
.iter()
.filter(|(_, score)| *score > 0.125)
.map(|(url, _score)| url.to_owned())
.collect();
Ok(relays)
}
// Get all the inboxes to post something to them
pub fn get_all_pubkey_inboxes(pubkey: PublicKey) -> Result<Vec<RelayUrl>
10BC8
, Error> {
// Why 0.125?
// if declared they will get an association score of at least 1.0
// by default based on relay rank, they will get a relay score of 0.33333
// modified by success rate, and 50% success rate will give 75% of this number, which is 0.25
// plus-connected cuts it in half if not connected, so 0.125, and we want to include all
// declared relays even that aren't connected down to 50% success rate.
let relays =
get_best_relays_with_score(pubkey, RelayUsage::Inbox, ScoreFactors::FULLY_ADJUSTED)?
.iter()
.filter(|(_, score)| *score > 0.125)
.map(|(url, _score)| url.to_owned())
.collect();
Ok(relays)
}
/// This gets NIP-17 DM relays only.
///
/// At the time of writing, not many people have these specified, in which case
/// the caller should fallback to write relays and NIP-04.
pub fn get_dm_relays(pubkey: PublicKey) -> Result<Vec<RelayUrl>, Error> {
let mut output: Vec<RelayUrl> = Vec::new();
for pr in GLOBALS.db().get_person_relays(pubkey)?.drain(..) {
let relay = GLOBALS.db().read_or_create_relay(&pr.url, None)?;
if relay.should_avoid() {
continue;
}
if pr.dm {
output.push(pr.url)
}
}
Ok(output)
}
// The functions below are all about choosing relays for some task,
// each returning `Result<Vec<RelayUrl>, Error>` (or similar)
/// This tries to generate a single RelayUrl to use for an 'e' or 'a' tag hint
pub fn recommended_relay_hint(reply_to: Id) -> Result<Option<RelayUrl>, Error> {
let seen_on_relays: Vec<(RelayUrl, Unixtime)> =
GLOBALS.db().get_event_seen_on_relay(reply_to)?;
let maybepubkey = GLOBALS.identity.public_key();
if let Some(pubkey) = maybepubkey {
let my_inbox_relays: Vec<RelayUrl> = get_all_pubkey_inboxes(pubkey)?;
// Find the first-best intersection
for mir in &my_inbox_relays {
for sor in &seen_on_relays {
if *mir == sor.0 {
return Ok(Some(mir.clone()));
}
}
}
// Else fall through to seen on relays only
}
if let Some(sor) = seen_on_relays.first() {
return Ok(Some(sor.0.clone()));
}
Ok(None)
}
// Which relays are best for a reply to this event (used to find replies to this event)
// FIXME this may go away once seeker uses 'sort relays' below, I'm not sure.
pub fn relays_for_seeking_replies(event: &Event) -> Result<Vec<RelayUrl>, Error> {
let mut relays: Vec<RelayUrl> = Vec::new();
// Inboxes of the author
relays.extend(get_all_pubkey_inboxes(event.pubkey)?);
// All of the user's READ relays
relays.extend(Relay::choose_relay_urls(Relay::READ, |_| true)?);
// Inboxes of the 'p' tagged people, up to num
//for (tagged_pubkey, _opt_relay_url, _opt_marker) in event.people() {
// relays.extend(get_all_reasonable_boxes(tagged_pubkey, RelayUsage::Inbox, num)?);
//}
if !GLOBALS
.db()
.read_setting_limit_inbox_seeking_to_inbox_relays()
{
// Seen on relays
let mut seen_on: Vec<RelayUrl> = GLOBALS
.db()
.get_event_seen_on_relay(event.id)?
.drain(..)
.map(|(url, _time)| url)
.collect();
// Take all inbox relays, and up to 2 seen_on relays that aren't inbox relays
let mut extra = 2;
for url in seen_on.drain(..) {
if extra == 0 {
break;
}
if relays.contains(&url) {
continue;
}
relays.push(url);
extra -= 1;
}
}
Ok(relays)
}
// Which relays should an event be posted to (that it hasn't already been
// seen on)? DO NOT USE for NIP-17 (we can't tell the recipient)
pub fn relays_to_post_to(event: &Event) -> Result<Vec<RelayUrl>, Error> {
let mut relays: Vec<RelayUrl> = Vec::new();
if event.kind == EventKind::GiftWrap || event.kind == EventKind::DmChat {
return Err(ErrorKind::Internal(
"DO NOT USE relays_to_post_to() for Giftwrap DMs".to_string(),
)
.into());
}
// All of my outboxes
relays.extend(Relay::choose_relay_urls(Relay::WRITE, |_| true)?);
// Inbox (or DM) relays of tagged people
let mut tagged_pubkeys: Vec<PublicKey> = event.people().iter().map(|(pk, _, _)| *pk).collect();
for pubkey in tagged_pubkeys.drain(..) {
let user_relays = get_all_pubkey_inboxes(pubkey)?;
if event.kind == EventKind::EncryptedDirectMessage {
let dm_relays = get_dm_relays(pubkey)?;
if dm_relays.is_empty() {
relays.extend(user_relays);
} else {
relays.extend(dm_relays);
}
} else {
relays.extend(user_relays);
}
}
// Remove all the 'seen_on' relays for this event
let seen_on: Vec<RelayUrl> = GLOBALS
.db()
.get_event_seen_on_relay(event.id)?
.iter()
.map(|(url, _time)| url.to_owned())
.collect();
relays.retain(|r| !seen_on.contains(r));
relays.sort();
relays.dedup();
Ok(relays)
}
/// Only RelayUsage::Outbox and RelayUsage::Inbox are supported.
///
/// Output scores range from 0.0 to 1.0
pub fn get_best_relays_with_score(
pubkey: PublicKey,
usage: RelayUsage,
score_factors: ScoreFactors,
) -> Result<Vec<(RelayUrl, f32)>, Error> {
if usage != RelayUsage::Outbox && usage != RelayUsage::Inbox {
return Err(ErrorKind::UnsupportedRelayUsage.into());
}
// Load person relays, filtering out banned URLs
let mut person_relays: Vec<PersonRelay> = GLOBALS
.db()
.get_person_relays(pubkey)?
.drain(..)
.filter(|pr| !crate::storage::Storage::url_is_banned(&pr.url))
.collect();
let mut strong: Vec<(RelayUrl, f32)> = Vec::new();
let mut weak: Vec<(RelayUrl, f32)> = Vec::new();
let now = Unixtime::now();
for pr in person_relays.drain(..) {
// Get their association to that relay
let association_score = pr.association_score(now, usage);
let relay = GLOBALS.db().read_or_create_relay(&pr.url, None)?;
if relay.should_avoid() {
continue;
}
let multiplier = relay.adjusted_score(score_factors);
// Multiply them (max is the relay score, or the association score)
let score = association_score * multiplier;
// Only accept declared relays
if association_score < 1.0 {
weak.push((pr.url, score));
} else {
strong.push((pr.url, score));
}
}
let mut output: Vec<(RelayUrl, f32)> = strong.clone();
if output.is_empty() {
output.extend(weak);
}
output.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
Ok(output)
}
/*
/// For seeking a KNOWN event (e.g. thread climbing, quoting) that we do not have, but which
/// may be related to certain relays or certain people, this function determines which relays
/// to look on in priority order. The list is not pruned or limited so that the seeker can
/// keep looking and never give up until it either finds it or it tried all the places
/// that we thought might be viable.
pub fn sort_relays(
mut hinted: Vec<RelayUrl>,
mut related_seen_on: Vec<RelayUrl>,
mut inboxes: Vec<PublicKey>,
mut outboxes: Vec<PublicKey>,
) -> Result<Vec<RelayUrl>, Error> {
struct RelayData {
score: f32,
bonus: f32, // fractions of 10
}
// For each URL, keep the relay record and a score
let mut map: HashMap<RelayUrl, RelayData> = HashMap::new();
// Load each hinted relay, gets 1 bonus point
for url in hinted.drain(..) {
let relay = GLOBALS.db().read_or_create_relay(&url, None)?;
let score = relay.score_plus_connected();
let relay_data = RelayData { score, bonus: 1.0 };
map.insert(url, relay_data);
}
// Load each seen on relay, gets 2 bonus points
for url in related_seen_on.drain(..) {
if let Some(data) = map.get_mut(&url) {
data.bonus += 2.0;
} else {
let relay = GLOBALS.db().read_or_create_relay(&url, None)?;
let score = relay.score_plus_connected();
let relay_data = RelayData { score, bonus: 2.0 };
map.insert(url, relay_data);
}
}
// Load inboxes
for pk in inboxes.drain(..) {
let mut relays: Vec<(RelayUrl, f32)> =
get_best_relays_with_score(pk, RelayUsage::Inbox, ScoreFactors::BASE)?;
for (url, pscore) in relays.drain(..) {
if let Some(data) = map.get_mut(&url) {
data.bonus += 5.0 * pscore;
} else {
let relay = GLOBALS.db().read_or_create_relay(&url, None)?;
let score = relay.score_plus_connected();
let relay_data = RelayData {
score,
bonus: 5.0 * pscore,
};
map.insert(url, relay_data);
}
}
}
// Load outboxes
for pk in outboxes.drain(..) {
let mut relays: Vec<(RelayUrl, f32)> =
get_best_relays_with_score(pk, RelayUsage::Outbox, ScoreFactors::BASE)?;
for (url, pscore) in relays.drain(..) {
if let Some(data) = map.get_mut(&url) {
data.bonus += 5.0 * pscore;
} else {
let relay = GLOBALS.db().read_or_create_relay(&url, None)?;
let score = relay.score_plus_connected();
let relay_data = RelayData {
score,
bonus: 5.0 * pscore,
};
map.insert(url, relay_data);
}
}
}
let mut vec: Vec<(RelayUrl, f32)> = map
.iter()
.map(|(url, data)| (url.to_owned(), data.score * 0.1 * data.bonus))
.collect();
vec.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
Ok(vec.iter().map(|(url, _)| url.to_owned()).collect())
}
*/