pkarr 5.0.4

Public-Key Addressable Resource Records (Pkarr); publish and resolve DNS records over Mainline DHT
Documentation
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
use std::collections::HashMap;
use std::fmt::Debug;
#[cfg(not(wasm_browser))]
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use bytes::Bytes;
use futures_buffered::FuturesUnorderedBounded;
#[cfg(not(wasm_browser))]
use futures_lite::Stream;
use futures_lite::StreamExt;
use ntimestamp::Timestamp;
use reqwest::Method;
use url::Url;

use reqwest::{
    header::{self, HeaderValue},
    Client, StatusCode,
};

use super::{ConcurrencyError, PublishError, QueryError};
use crate::{PublicKey, SignedPacket};

#[derive(Clone)]
pub struct RelaysClient {
    relays: Box<[Url]>,
    http_client: Client,
    timeout: Duration,
    pub(crate) inflight_publish: InflightPublishRequests,
}

impl Debug for RelaysClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut debug_struct = f.debug_struct("RelaysClient");

        debug_struct.field(
            "relays",
            &self
                .relays
                .as_ref()
                .iter()
                .map(|url| url.as_str())
                .collect::<Vec<_>>(),
        );

        debug_struct.finish()
    }
}

impl RelaysClient {
    pub fn new(relays: Box<[Url]>, timeout: Duration) -> Self {
        let inflight_publish = InflightPublishRequests::new(relays.len());

        Self {
            relays,
            http_client: Client::builder()
                .build()
                .expect("Client building should be infallible"),

            timeout,
            inflight_publish,
        }
    }

    pub async fn publish(
        &self,
        signed_packet: &SignedPacket,
        cas: Option<Timestamp>,
    ) -> Result<(), PublishError> {
        let public_key = signed_packet.public_key();

        self.inflight_publish
            .start_request(&public_key, signed_packet, cas)?;

        let mut futures = futures_buffered::FuturesUnorderedBounded::new(self.relays.len());

        let body = signed_packet.to_relay_payload();
        let cas = cas.map(|timestamp| timestamp.as_u64().to_string());

        for relay in &self.relays {
            let http_client = self.http_client.clone();
            let timeout = self.timeout;

            let cas = cas.clone();
            let body = body.clone();

            let public_key = public_key.clone();
            let relay = relay.clone();

            let mut inflight = self.inflight_publish.clone();

            futures.push(async move {
                let result = publish_to_relay(http_client, relay, &public_key, body, cas, timeout)
                    .await
                    .map_err(map_reqwest_error);

                inflight.add_result(&public_key, result)
            });
        }

        futures
            .filter_map(|result| match result {
                Ok(true) => Some(Ok(())),
                Ok(false) => None,
                Err(err) => Some(Err(err)),
            })
            .next()
            .await
            .expect("relays inflight publish requests done with no success or error!")
    }

    #[cfg(not(wasm_browser))]
    /// Cancel an inflight publish request.
    pub fn cancel_publish(&self, public_key: &PublicKey) {
        self.inflight_publish.cancel_request(public_key);
    }

    #[cfg(not(wasm_browser))]
    pub fn resolve(
        &self,
        public_key: &PublicKey,
        more_recent_than: Option<Timestamp>,
    ) -> Pin<Box<dyn Stream<Item = SignedPacket> + Send>> {
        Box::pin(
            self.resolve_futures(public_key, more_recent_than)
                .filter_map(|opt| opt),
        )
    }

    pub fn resolve_futures(
        &self,
        public_key: &PublicKey,
        more_recent_than: Option<Timestamp>,
    ) -> FuturesUnorderedBounded<impl futures_lite::Future<Output = Option<SignedPacket>>> {
        let mut futures = FuturesUnorderedBounded::new(self.relays.len());

        let if_modified_since = more_recent_than.map(|t| t.format_http_date());

        self.relays.iter().for_each(|relay| {
            let http_client = self.http_client.clone();
            let relay = relay.clone();
            let public_key = public_key.clone();
            let if_modified_since = if_modified_since.clone();
            let timeout = self.timeout;

            futures.push(resolve_from_relay(
                http_client,
                relay,
                public_key,
                if_modified_since,
                timeout,
            ));
        });

        futures
    }
}

#[derive(Debug)]
struct InflightPublishRequest {
    signed_packet: SignedPacket,
    success_count: usize,
    errors: HashMap<PublishError, usize>,
}

#[derive(Clone, Debug)]
pub(crate) struct InflightPublishRequests {
    relays_count: usize,
    requests: Arc<Mutex<HashMap<PublicKey, InflightPublishRequest>>>,
}

impl InflightPublishRequests {
    fn new(relays_count: usize) -> Self {
        Self {
            relays_count,
            requests: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    pub fn start_request(
        &self,
        public_key: &PublicKey,
        signed_packet: &SignedPacket,
        cas: Option<Timestamp>,
    ) -> Result<(), PublishError> {
        let mut requests = self.requests.lock().expect("InflightPublishRequests lock");

        if let Some(inflight_request) = requests.get_mut(public_key) {
            if signed_packet.signature() == inflight_request.signed_packet.signature() {
                // No-op, the inflight query is sufficient.
            } else if !signed_packet.more_recent_than(&inflight_request.signed_packet) {
                return Err(ConcurrencyError::NotMostRecent)?;
            } else if let Some(cas) = cas {
                if cas != inflight_request.signed_packet.timestamp() {
                    return Err(ConcurrencyError::CasFailed)?;
                }
            } else {
                return Err(ConcurrencyError::ConflictRisk)?;
            };
        } else {
            requests.insert(
                public_key.clone(),
                InflightPublishRequest {
                    signed_packet: signed_packet.clone(),
                    success_count: 0,
                    errors: Default::default(),
                },
            );
        };

        Ok(())
    }

    #[cfg(not(wasm_browser))]
    pub fn cancel_request(&self, public_key: &PublicKey) {
        let mut inflight = self.requests.lock().expect("InflightPublishRequests lock");

        inflight.remove(public_key);
    }

    pub fn add_result(
        &mut self,
        public_key: &PublicKey,
        result: Result<(), PublishError>,
    ) -> Result<bool, PublishError> {
        match result {
            Ok(_) => self.add_success(public_key),
            Err(error) => self.add_error(public_key, error),
        }
    }

    /// Returns true if request is done.
    fn add_success(&self, public_key: &PublicKey) -> Result<bool, PublishError> {
        let mut inflight = self.requests.lock().expect("InflightPublishRequests lock");

        if let Some(request) = inflight.get_mut(public_key) {
            let majority = self.relays_count / 2 + self.relays_count % 2;

            request.success_count += 1;

            if self.done(request) || request.success_count >= majority {
                inflight.remove(public_key);

                Ok(true)
            } else {
                Ok(false)
            }
        } else {
            Ok(true)
        }
    }

    /// Returns true if request is done.
    fn add_error(
        &mut self,
        public_key: &PublicKey,
        error: PublishError,
    ) -> Result<bool, PublishError> {
        let mut inflight = self.requests.lock().expect("InflightPublishRequests lock");

        if let Some(request) = inflight.get_mut(public_key) {
            let majority = self.relays_count / 2 + self.relays_count % 2;

            // Add error, and return early error if necessary.
            {
                let count = request.errors.get(&error).unwrap_or(&0) + 1;

                if count >= majority
                    && matches!(
                        error,
                        PublishError::Concurrency(ConcurrencyError::NotMostRecent)
                    ) | matches!(
                        error,
                        PublishError::Concurrency(ConcurrencyError::CasFailed)
                    )
                {
                    inflight.remove(public_key);

                    return Err(error);
                }

                request.errors.insert(error, count);
            }

            if self.done(request) {
                let request = inflight.remove(public_key).expect("infallible");

                if request.success_count >= majority {
                    Ok(true)
                } else {
                    let most_common_error = request
                        .errors
                        .into_iter()
                        .max_by_key(|&(_, count)| count)
                        .map(|(error, _)| error)
                        .expect("infallible");

                    Err(most_common_error)
                }
            } else {
                Ok(false)
            }
        } else {
            Ok(true)
        }
    }

    fn done(&self, request: &InflightPublishRequest) -> bool {
        let total_errors: usize = request.errors.values().sum();
        (total_errors + request.success_count) >= self.relays_count
    }
}

pub async fn publish_to_relay(
    http_client: reqwest::Client,
    relay: Url,
    public_key: &PublicKey,
    body: Bytes,
    cas: Option<String>,
    timeout: Duration,
) -> Result<(), reqwest::Error> {
    let url = format_url(&relay, public_key);

    let mut request = http_client.put(url.clone());

    request = request
        // Publish combines the http latency with the PUT query to the dht
        // on the relay side, so we should be as generous as possible
        .timeout(timeout * 3);

    if let Some(cas) = cas {
        request = request.header(header::IF_MATCH, cas);
    }

    let response = request.body(body).send().await.inspect_err(|error| {
        cross_debug!("PUT {:?}", error);
    })?;

    let status = response.status();

    if let Err(error) = response.error_for_status_ref() {
        let text = response.text().await.unwrap_or("".to_string());

        cross_debug!("Got error response for PUT {url} {status} {text}");

        return Err(error);
    };

    if status.is_success() {
        cross_debug!("Successfully published to {url}");
    } else {
        cross_debug!("Got neither 2xx nor >=400 status code {status} for PUT {url}",);
    }

    Ok(())
}

fn map_reqwest_error(error: reqwest::Error) -> PublishError {
    if error.is_timeout() {
        PublishError::Query(QueryError::Timeout)
    } else if error.is_status() {
        match error
            .status()
            .expect("previously verified that it is a status error")
        {
            StatusCode::BAD_REQUEST => {
                // This should be very unlikely unless relays are misbehaving, still worth
                // returning to the user to know that relays are misbehaving, and not just a
                // network issue.
                PublishError::Query(QueryError::BadRequest)
            }
            StatusCode::CONFLICT => PublishError::Concurrency(ConcurrencyError::NotMostRecent),
            StatusCode::PRECONDITION_FAILED => {
                PublishError::Concurrency(ConcurrencyError::CasFailed)
            }
            StatusCode::PRECONDITION_REQUIRED => {
                PublishError::Concurrency(ConcurrencyError::ConflictRisk)
            }
            _ => PublishError::UnexpectedResponses,
        }
    } else {
        PublishError::UnexpectedResponses
    }
}

pub fn format_url(relay: &Url, public_key: &PublicKey) -> Url {
    let mut url = relay.clone();

    let mut segments = url
        .path_segments_mut()
        .expect("Relay url cannot be base, is it http(s)?");

    segments.push(&public_key.to_string());

    drop(segments);

    url
}

pub async fn resolve_from_relay(
    http_client: reqwest::Client,
    relay: Url,
    public_key: PublicKey,
    if_modified_since: Option<String>,
    timeout: Duration,
) -> Option<SignedPacket> {
    let url = format_url(&relay, &public_key);

    let mut request = reqwest::Request::new(Method::GET, url.clone());

    *request.timeout_mut() = Some(timeout);

    if let Some(ref httpdate) = if_modified_since {
        request.headers_mut().insert(
            header::IF_MODIFIED_SINCE,
            HeaderValue::from_str(httpdate).expect("httpdate to be valid header value"),
        );
    }

    let response = loop {
        let response = match http_client
            .execute(request.try_clone().expect("infallible"))
            .await
        {
            Ok(response) => response,
            Err(error) => {
                cross_debug!("GET {:?}", error);

                return None;
            }
        };

        let status = response.status();

        if response.error_for_status_ref().is_err() {
            let text = response.text().await.unwrap_or("".to_string());

            cross_debug!("Got error response for GET {url} {status} {text}");

            return None;
        };

        if should_retry_with_cache_disabled(
            &mut request,
            &if_modified_since,
            &status,
            response.content_length(),
        ) {
            continue;
        } else {
            break response;
        }
    };

    if response.content_length().unwrap_or_default() > SignedPacket::MAX_BYTES {
        cross_debug!("Response too large for GET {url}");

        return None;
    }

    let payload = match response.bytes().await {
        Ok(payload) => payload,
        Err(error) => {
            cross_debug!("Failed to read relay response from GET {url} {error}");

            return None;
        }
    };

    match SignedPacket::from_relay_payload(&public_key, &payload) {
        Ok(signed_packet) => Some(signed_packet),
        Err(error) => {
            cross_debug!("Invalid signed_packet {url}:{error}");

            None
        }
    }
}

fn should_retry_with_cache_disabled(
    request: &mut reqwest::Request,
    if_modified_since: &Option<String>,
    status: &StatusCode,
    content_length: Option<u64>,
) -> bool {
    // We got a 304 not modified, even though we don't have any packet in cache.
    let unexpected_not_modified =
        (*status == StatusCode::NOT_MODIFIED) && if_modified_since.is_none();

    // We got a success response, but the packet is empty.
    let broken_cache = status.is_success() && (content_length.unwrap_or_default() == 0);

    let needs_retry_with_cache_disabled = unexpected_not_modified || broken_cache;

    let havent_retried_with_cache_disabled_already =
        request.headers().get(header::CACHE_CONTROL).is_none();

    if needs_retry_with_cache_disabled && havent_retried_with_cache_disabled_already {
        request.headers_mut().insert(
            header::CACHE_CONTROL,
            "no-cache, no-store, must-revalidate"
                .try_into()
                .expect("cache control is valid http header value"),
        );

        return true;
    }

    false
}