distributed-topic-tracker 0.3.1

automagically find peers interested in a topic + iroh-gossip integration
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
use std::{
    collections::{HashMap, HashSet},
    str::FromStr,
};

use anyhow::{Result, bail};
use ed25519_dalek::{Signer, SigningKey, VerifyingKey};
use getrandom::{SysRng, rand_core::UnwrapErr};

use ed25519_dalek_hpke::{Ed25519hpkeDecryption, Ed25519hpkeEncryption};
use serde::{Deserialize, Serialize};
use sha2::Digest;
use tokio_util::sync::CancellationToken;

use crate::Config;

/// Topic identifier derived from a string via SHA512 hashing.
///
/// Used as the stable identifier for gossip subscriptions and DHT records.
///
/// # Example
///
/// ```ignore
/// let topic_id = TopicId::new("chat-room-1".to_string());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TopicId([u8; 32]);

impl FromStr for TopicId {
    type Err = anyhow::Error;

    fn from_str(topic_name: &str) -> std::result::Result<Self, Self::Err> {
        Ok(Self::new(topic_name.to_string()))
    }
}

impl From<&str> for TopicId {
    fn from(topic_name: &str) -> Self {
        Self::new(topic_name.to_string())
    }
}

impl From<String> for TopicId {
    fn from(topic_name: String) -> Self {
        Self::new(topic_name)
    }
}
/// Treats `bytes` as a topic *name* and SHA-512 hashes them.
/// For a pre-computed 32-byte hash, use [`TopicId::from_hash`] instead.
impl From<Vec<u8>> for TopicId {
    fn from(topic_name: Vec<u8>) -> Self {
        Self::new(topic_name)
    }
}

impl TopicId {
    /// Create a new topic ID from a string.
    ///
    /// String is hashed with SHA512; the first 32 bytes produce the identifier.
    pub fn new(topic_name: impl Into<Vec<u8>>) -> Self {
        let mut topic_name_hash = sha2::Sha512::new();
        topic_name_hash.update(topic_name.into());

        Self(
            topic_name_hash.finalize()[..32]
                .try_into()
                .expect("hashing 'topic_name' failed"),
        )
    }

    /// Create from a pre-computed 32-byte hash.
    pub fn from_hash(bytes: &[u8; 32]) -> Self {
        Self(*bytes)
    }

    /// Get the hash bytes.
    pub fn hash(&self) -> [u8; 32] {
        self.0
    }
}

/// DHT record encrypted with HPKE.
///
/// Contains encrypted record data and encrypted decryption key.
/// Decryption requires the corresponding private key.
#[derive(Debug, Clone)]
pub struct EncryptedRecord {
    encrypted_record: Vec<u8>,
    encrypted_decryption_key: Vec<u8>,
}

/// A signed DHT record containing peer discovery information.
///
/// Records are timestamped, signed, and include content about active peers
/// and recent messages for bubble detection and message overlap merging.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Record {
    topic: [u8; 32],
    unix_minute: u64,
    pub_key: [u8; 32],
    content: RecordContent,
    signature: [u8; 64],
}

/// Serializable content of a DHT record.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RecordContent(pub Vec<u8>);

impl RecordContent {
    /// Deserialize using postcard codec.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let content: GossipRecordContent = record_content.to()?;
    /// ```
    pub fn to<'a, T: Deserialize<'a>>(&'a self) -> anyhow::Result<T> {
        postcard::from_bytes::<T>(&self.0).map_err(|e| anyhow::anyhow!(e))
    }

    /// Serialize from an arbitrary type using postcard.
    pub fn from_arbitrary<T: Serialize>(from: &T) -> anyhow::Result<Self> {
        Ok(Self(
            postcard::to_allocvec(from).map_err(|e| anyhow::anyhow!(e))?,
        ))
    }
}

/// Publisher for creating and distributing signed DHT records.
///
/// Checks existing DHT record count before publishing to respect capacity limits.
#[derive(Debug, Clone)]
pub struct RecordPublisher {
    dht: crate::dht::Dht,

    config: crate::config::Config,

    topic_id: TopicId,
    pub_key: VerifyingKey,
    signing_key: SigningKey,
    secret_rotation: Option<crate::crypto::keys::RotationHandle>,
    initial_secret_hash: [u8; 32],
}

/// Builder for `RecordPublisher`.
#[derive(Debug)]
pub struct RecordPublisherBuilder {
    topic_id: TopicId,
    signing_key: SigningKey,
    secret_rotation: Option<crate::crypto::keys::RotationHandle>,
    initial_secret: Vec<u8>,
    config: crate::config::Config,
}

impl RecordPublisherBuilder {
    /// Set a custom secret rotation strategy.
    pub fn secret_rotation(mut self, secret_rotation: crate::crypto::keys::RotationHandle) -> Self {
        self.secret_rotation = Some(secret_rotation);
        self
    }

    /// Set the configuration.
    pub fn config(mut self, config: crate::config::Config) -> Self {
        self.config = config;
        self
    }

    /// Build the `RecordPublisher`.
    pub fn build(self) -> RecordPublisher {
        RecordPublisher::new(
            self.topic_id,
            self.signing_key,
            self.secret_rotation,
            self.initial_secret,
            self.config,
        )
    }
}

impl RecordPublisher {
    /// Create a new `RecordPublisherBuilder`.
    pub fn builder(
        topic_id: impl Into<TopicId>,
        signing_key: SigningKey,
        initial_secret: impl Into<Vec<u8>>,
    ) -> RecordPublisherBuilder {
        RecordPublisherBuilder {
            topic_id: topic_id.into(),
            signing_key,
            secret_rotation: None,
            initial_secret: initial_secret.into(),
            config: crate::config::Config::default(),
        }
    }

    /// Create a new record publisher.
    ///
    /// # Arguments
    ///
    /// * `topic_id` - Topic identifier
    /// * `signing_key` - Ed25519 secret key (signing key)
    /// * `secret_rotation` - Optional custom key rotation strategy
    /// * `initial_secret` - Initial secret for key derivation
    /// * `config` - Configuration settings
    pub fn new(
        topic_id: impl Into<TopicId>,
        signing_key: SigningKey,
        secret_rotation: Option<crate::crypto::keys::RotationHandle>,
        initial_secret: impl Into<Vec<u8>>,
        config: crate::config::Config,
    ) -> Self {
        let mut initial_secret_hash = sha2::Sha512::new();
        initial_secret_hash.update(initial_secret.into());
        let initial_secret_hash: [u8; 32] = initial_secret_hash.finalize()[..32]
            .try_into()
            .expect("hashing failed");

        Self {
            dht: crate::dht::Dht::new(config.dht_config()),
            config,
            topic_id: topic_id.into(),
            pub_key: signing_key.verifying_key(),
            signing_key,
            secret_rotation,
            initial_secret_hash,
        }
    }

    /// Create a new signed record with content.
    ///
    /// # Arguments
    ///
    /// * `unix_minute` - Time slot for this record
    /// * `record_content` - Serializable content
    pub fn new_record<'a>(
        &'a self,
        unix_minute: u64,
        record_content: impl Serialize + Deserialize<'a>,
    ) -> Result<Record> {
        Record::sign(
            self.topic_id.hash(),
            unix_minute,
            record_content,
            &self.signing_key,
        )
    }

    /// Get this publisher's Ed25519 verifying key.
    pub fn pub_key(&self) -> ed25519_dalek::VerifyingKey {
        self.pub_key
    }

    /// Get TopicId.
    pub fn topic_id(&self) -> &TopicId {
        &self.topic_id
    }

    /// Get the signing key.
    pub fn signing_key(&self) -> &ed25519_dalek::SigningKey {
        &self.signing_key
    }

    /// Get the secret rotation handle if set.
    pub fn secret_rotation(&self) -> Option<crate::crypto::keys::RotationHandle> {
        self.secret_rotation.clone()
    }

    /// Get the initial secret hash.
    pub fn initial_secret_hash(&self) -> [u8; 32] {
        self.initial_secret_hash
    }

    /// Get the configuration.
    pub fn config(&self) -> &Config {
        &self.config
    }
}

impl RecordPublisher {
    /// Publish a record to the DHT if slot capacity allows.
    ///
    /// Checks existing record count for this time slot and skips publishing if
    /// `self.config.bootstrap_config().max_bootstrap_records()` limit reached.
    pub async fn publish_record(&self, record: Record, cancel_token: CancellationToken) -> Result<()> {
        self.publish_record_cached_records(record, None, cancel_token).await
    }

    /// Publish a record to the DHT (using cached get_records) if slot capacity allows.
    ///
    /// Checks existing record count for this time slot and skips publishing if
    /// `self.config.bootstrap_config().max_bootstrap_records()` limit reached.
    pub async fn publish_record_cached_records(
        &self,
        record: Record,
        cached_records: Option<HashSet<Record>>,
        cancel_token: CancellationToken,
    ) -> Result<()> {
        let publish_fut = async {
            let records = match cached_records {
                Some(records) => records,
                None => self.get_records(record.unix_minute(), cancel_token.clone()).await?,
            };

            tracing::debug!(
                "RecordPublisher: found {} existing records for unix_minute {}",
                records.len(),
                record.unix_minute()
            );

            if records.len() >= self.config.bootstrap_config().max_bootstrap_records() {
                tracing::debug!(
                    "RecordPublisher: max records reached ({}), skipping publish",
                    self.config.bootstrap_config().max_bootstrap_records()
                );
                return Ok(());
            }

            // Publish own records
            let sign_key = crate::crypto::keys::signing_keypair(self.topic_id(), record.unix_minute);
            let salt = crate::crypto::keys::salt(self.topic_id(), record.unix_minute);
            let encryption_key = crate::crypto::keys::encryption_keypair(
                self.topic_id(),
                &self.secret_rotation.clone().unwrap_or_default(),
                self.initial_secret_hash,
                record.unix_minute,
            );
            let encrypted_record = record.encrypt(&encryption_key);
            let next_seq_num = i64::MAX;

            tracing::debug!(
                "RecordPublisher: publishing record to DHT for unix_minute {}",
                record.unix_minute()
            );

            self.dht
                .put_mutable(
                    sign_key.clone(),
                    Some(salt.to_vec()),
                    encrypted_record.to_bytes()?,
                    next_seq_num,
                )
                .await?;

            tracing::debug!("RecordPublisher: successfully published to DHT");
            Ok(())
        };

        tokio::select! {
            _ = cancel_token.cancelled() => {
                anyhow::bail!("publish cancelled");
            }
            res = publish_fut => {
                res
            }
        }
    }

    /// Retrieve all verified records for a given time slot from the DHT.
    ///
    /// Filters out records from this publisher's own node ID.
    /// Dedup's records based on pub_key, keeping the highest sequence number per pub_key.
    pub async fn get_records(&self, unix_minute: u64, cancel_token: CancellationToken) -> Result<HashSet<Record>> {
        let get_fut = async {
            tracing::debug!(
                "RecordPublisher: fetching records from DHT for unix_minute {}",
                unix_minute
            );

            let topic_sign = crate::crypto::keys::signing_keypair(self.topic_id(), unix_minute);
            let encryption_key = crate::crypto::keys::encryption_keypair(
                self.topic_id(),
                &self.secret_rotation.clone().unwrap_or_default(),
                self.initial_secret_hash,
                unix_minute,
            );
            let salt = crate::crypto::keys::salt(self.topic_id(), unix_minute);

            // Get records, decrypt and verify
            let records_iter = self
                .dht
                .get(topic_sign.verifying_key(), Some(salt.to_vec()), None)
                .await?;

            tracing::debug!(
                "RecordPublisher: received {} raw records from DHT",
                records_iter.len()
            );

            let mut dedubed_records = HashMap::new();
            for item in records_iter {
                if let Ok(encrypted_record) = EncryptedRecord::from_bytes(item.value().to_vec())
                    && let Ok(record) = encrypted_record.decrypt(&encryption_key)
                    && record.verify(&self.topic_id.hash(), unix_minute).is_ok()
                    && !record.pub_key().eq(self.pub_key.as_bytes())
                {
                    let pub_key = record.pub_key();
                    match dedubed_records.get(&pub_key) {
                        Some((seq, _)) if *seq >= item.seq() => {}
                        _ => {
                            dedubed_records.insert(pub_key, (item.seq(), record));
                        }
                    }
                }
            }
            tracing::debug!(
                "RecordPublisher: verified {} records (filtered self)",
                dedubed_records.len()
            );

            Ok(dedubed_records
                .into_values()
                .map(|(_, record)| record)
                .collect::<HashSet<_>>())
        };

        tokio::select! {
            _ = cancel_token.cancelled() => {
                anyhow::bail!("get_records cancelled");
            }
            res = get_fut => {
                res
            }
        }
    }
}

impl EncryptedRecord {
    const MAX_SIZE: usize = 2048;

    /// Decrypt using an Ed25519 HPKE private key.
    pub fn decrypt(&self, decryption_key: &ed25519_dalek::SigningKey) -> Result<Record> {
        let one_time_key_bytes: [u8; 32] = decryption_key
            .decrypt(&self.encrypted_decryption_key)?
            .as_slice()
            .try_into()?;
        let one_time_key = ed25519_dalek::SigningKey::from_bytes(&one_time_key_bytes);

        let decrypted_record = one_time_key.decrypt(&self.encrypted_record)?;
        let record = Record::from_bytes(decrypted_record)?;
        Ok(record)
    }

    /// Serialize to bytes (length-prefixed format).
    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        let mut buf = Vec::new();
        let encrypted_record_len = self.encrypted_record.len() as u32;
        buf.extend_from_slice(&encrypted_record_len.to_le_bytes());
        buf.extend_from_slice(&self.encrypted_record);
        buf.extend_from_slice(&self.encrypted_decryption_key);

        if buf.len() > Self::MAX_SIZE {
            bail!(
                "EncryptedRecord serialization exceeds maximum size, the max is set generously so this should never happen, if so your code is using it manually"
            );
        }
        Ok(buf)
    }

    /// Deserialize from bytes.
    pub fn from_bytes(buf: Vec<u8>) -> Result<Self> {
        if buf.len() < 4 {
            bail!("buffer too short for EncryptedRecord deserialization")
        }
        let (encrypted_record_len, buf) = buf.split_at(4);
        let encrypted_record_len = u32::from_le_bytes(encrypted_record_len.try_into()?);
        const ENCRYPTED_KEY_LENGTH: usize = 88;
        let expected_payload_len = encrypted_record_len
            .checked_add(ENCRYPTED_KEY_LENGTH as u32)
            .ok_or_else(|| anyhow::anyhow!("encrypted record length overflow"))?;
        if encrypted_record_len > Self::MAX_SIZE as u32 {
            bail!("encrypted record length exceeds maximum allowed size")
        }
        if buf.len() != expected_payload_len as usize {
            bail!("buffer length does not match expected encrypted record length")
        }
        let (encrypted_record, encrypted_decryption_key) =
            buf.split_at(encrypted_record_len as usize);

        Ok(Self {
            encrypted_record: encrypted_record.to_vec(),
            encrypted_decryption_key: encrypted_decryption_key.to_vec(),
        })
    }
}

impl Record {
    /// Create and sign a new record.
    pub fn sign<'a>(
        topic: [u8; 32],
        unix_minute: u64,
        record_content: impl Serialize + Deserialize<'a>,
        signing_key: &ed25519_dalek::SigningKey,
    ) -> anyhow::Result<Self> {
        let record_content = RecordContent::from_arbitrary(&record_content)?;
        let mut signature_data = Vec::new();
        signature_data.extend_from_slice(&topic);
        signature_data.extend_from_slice(&unix_minute.to_le_bytes());
        signature_data.extend_from_slice(&signing_key.verifying_key().to_bytes());
        signature_data.extend(&record_content.clone().0);
        let signature = signing_key.sign(&signature_data);
        Ok(Self {
            topic,
            unix_minute,
            pub_key: signing_key.verifying_key().to_bytes(),
            content: record_content,
            signature: signature.to_bytes(),
        })
    }

    /// Deserialize from bytes.
    pub fn from_bytes(buf: Vec<u8>) -> Result<Self> {
        if buf.len() < 32 + 8 + 32 + 64 {
            bail!("buffer too short for Record deserialization")
        }
        let (topic, buf) = buf.split_at(32);
        let (unix_minute, buf) = buf.split_at(8);
        let (pub_key, buf) = buf.split_at(32);
        let (record_content, buf) = buf.split_at(buf.len() - 64);

        let (signature, buf) = buf.split_at(64);

        if !buf.is_empty() {
            bail!("buffer not empty after reconstruction")
        }

        Ok(Self {
            topic: topic.try_into()?,
            unix_minute: u64::from_le_bytes(unix_minute.try_into()?),
            pub_key: pub_key.try_into()?,
            content: RecordContent(record_content.to_vec()),
            signature: signature.try_into()?,
        })
    }

    /// Serialize to bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        buf.extend_from_slice(&self.topic);
        buf.extend_from_slice(&self.unix_minute.to_le_bytes());
        buf.extend_from_slice(&self.pub_key);
        buf.extend(&self.content.0);
        buf.extend_from_slice(&self.signature);
        buf
    }

    /// Verify signature against topic and timestamp.
    pub fn verify(&self, actual_topic: &[u8; 32], actual_unix_minute: u64) -> Result<()> {
        if self.topic != *actual_topic {
            bail!("topic mismatch")
        }
        if self.unix_minute != actual_unix_minute {
            bail!("unix minute mismatch")
        }

        let record_bytes = self.to_bytes();
        let signature_data = record_bytes[..record_bytes.len() - 64].to_vec();
        let signature = ed25519_dalek::Signature::from_bytes(&self.signature);
        let pub_key = ed25519_dalek::VerifyingKey::from_bytes(&self.pub_key)?;

        pub_key.verify_strict(signature_data.as_slice(), &signature)?;

        Ok(())
    }

    /// Encrypt record with HPKE.
    pub fn encrypt(&self, encryption_key: &ed25519_dalek::SigningKey) -> EncryptedRecord {
        let mut csprng = UnwrapErr(SysRng);
        let one_time_key = ed25519_dalek::SigningKey::generate(&mut csprng);
        let p_key = one_time_key.verifying_key();
        let data_enc = p_key.encrypt(&self.to_bytes()).expect("encryption failed");
        let key_enc = encryption_key
            .verifying_key()
            .encrypt(&one_time_key.to_bytes())
            .expect("encryption failed");

        EncryptedRecord {
            encrypted_record: data_enc,
            encrypted_decryption_key: key_enc,
        }
    }
}

// Field accessors
impl Record {
    /// Get the topic hash.
    pub fn topic(&self) -> [u8; 32] {
        self.topic
    }

    /// Get the Unix minute timestamp.
    pub fn unix_minute(&self) -> u64 {
        self.unix_minute
    }

    /// Get the pub_key (publisher's public key).
    pub fn pub_key(&self) -> [u8; 32] {
        self.pub_key
    }

    /// Deserialize the record content.
    pub fn content<'a, T: Deserialize<'a>>(&'a self) -> anyhow::Result<T> {
        self.content.to::<T>()
    }

    /// Get the raw signature bytes.
    pub fn signature(&self) -> [u8; 64] {
        self.signature
    }
}