katzenpost_thin_client 0.0.17

This rust crate provides an async thin client library for Katzenpost, a post quantum decryption mixnet.
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
// SPDX-FileCopyrightText: Copyright (C) 2026 David Stainton
// SPDX-License-Identifier: AGPL-3.0-only

//! Database layer for pigeonhole state persistence.

use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};

use rusqlite::{Connection, params};

use super::error::{PigeonholeDbError, Result};
use super::models::{PendingMessage, ReadChannel, ReceivedMessage, WriteChannel};

/// Database handle for pigeonhole state.
#[derive(Clone)]
pub struct Database {
    conn: Arc<Mutex<Connection>>,
}

impl Database {
    /// Open or create a database at the given path.
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        let conn = Connection::open(path)?;
        let db = Self { conn: Arc::new(Mutex::new(conn)) };
        db.init_schema()?;
        Ok(db)
    }

    /// Open an in-memory database (useful for testing).
    pub fn open_in_memory() -> Result<Self> {
        let conn = Connection::open_in_memory()?;
        let db = Self { conn: Arc::new(Mutex::new(conn)) };
        db.init_schema()?;
        Ok(db)
    }

    fn init_schema(&self) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute_batch(
            r#"
            CREATE TABLE IF NOT EXISTS write_channels (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL UNIQUE,
                write_cap BLOB NOT NULL,
                next_index BLOB NOT NULL,
                created_at INTEGER NOT NULL,
                updated_at INTEGER NOT NULL
            );

            CREATE TABLE IF NOT EXISTS read_channels (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL UNIQUE,
                read_cap BLOB NOT NULL,
                next_index BLOB NOT NULL,
                created_at INTEGER NOT NULL,
                updated_at INTEGER NOT NULL
            );

            CREATE TABLE IF NOT EXISTS pending_messages (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                write_channel_id INTEGER NOT NULL,
                plaintext BLOB NOT NULL,
                message_ciphertext BLOB NOT NULL,
                envelope_descriptor BLOB NOT NULL,
                envelope_hash BLOB NOT NULL UNIQUE,
                box_index BLOB NOT NULL,
                attempts INTEGER NOT NULL DEFAULT 0,
                status TEXT NOT NULL DEFAULT 'pending',
                created_at INTEGER NOT NULL,
                last_attempt_at INTEGER,
                FOREIGN KEY (write_channel_id) REFERENCES write_channels(id) ON DELETE CASCADE
            );

            CREATE TABLE IF NOT EXISTS received_messages (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                read_channel_id INTEGER NOT NULL,
                plaintext BLOB NOT NULL,
                box_index BLOB NOT NULL,
                received_at INTEGER NOT NULL,
                is_read INTEGER NOT NULL DEFAULT 0,
                FOREIGN KEY (read_channel_id) REFERENCES read_channels(id) ON DELETE CASCADE
            );

            CREATE INDEX IF NOT EXISTS idx_pending_status ON pending_messages(status);
            CREATE INDEX IF NOT EXISTS idx_pending_write_channel ON pending_messages(write_channel_id);
            CREATE INDEX IF NOT EXISTS idx_received_read_channel ON received_messages(read_channel_id);
            CREATE INDEX IF NOT EXISTS idx_received_unread ON received_messages(is_read);
            "#,
        )?;
        Ok(())
    }

    fn now() -> i64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64
    }

    // ========================================================================
    // Write Channel Operations
    // ========================================================================

    pub fn create_write_channel(
        &self,
        name: &str,
        write_cap: &[u8],
        next_index: &[u8],
    ) -> Result<WriteChannel> {
        let conn = self.conn.lock().unwrap();
        let now = Self::now();

        conn.execute(
            r#"INSERT INTO write_channels (name, write_cap, next_index, created_at, updated_at)
               VALUES (?1, ?2, ?3, ?4, ?5)"#,
            params![name, write_cap, next_index, now, now],
        ).map_err(|e| match e {
            rusqlite::Error::SqliteFailure(ref err, _)
                if err.code == rusqlite::ErrorCode::ConstraintViolation =>
            {
                PigeonholeDbError::ChannelAlreadyExists(name.to_string())
            }
            other => PigeonholeDbError::Database(other),
        })?;

        let id = conn.last_insert_rowid();
        Ok(WriteChannel {
            id,
            name: name.to_string(),
            write_cap: write_cap.to_vec(),
            next_index: next_index.to_vec(),
            created_at: now,
            updated_at: now,
        })
    }

    pub fn get_write_channel(&self, name: &str) -> Result<WriteChannel> {
        let conn = self.conn.lock().unwrap();
        let mut stmt = conn.prepare(
            "SELECT id, name, write_cap, next_index, created_at, updated_at \
             FROM write_channels WHERE name = ?1",
        )?;

        stmt.query_row(params![name], |row| {
            Ok(WriteChannel {
                id: row.get(0)?,
                name: row.get(1)?,
                write_cap: row.get(2)?,
                next_index: row.get(3)?,
                created_at: row.get(4)?,
                updated_at: row.get(5)?,
            })
        }).map_err(|e| match e {
            rusqlite::Error::QueryReturnedNoRows => PigeonholeDbError::ChannelNotFound(name.to_string()),
            other => PigeonholeDbError::Database(other),
        })
    }

    pub fn get_write_channel_by_id(&self, id: i64) -> Result<WriteChannel> {
        let conn = self.conn.lock().unwrap();
        let mut stmt = conn.prepare(
            "SELECT id, name, write_cap, next_index, created_at, updated_at \
             FROM write_channels WHERE id = ?1",
        )?;

        stmt.query_row(params![id], |row| {
            Ok(WriteChannel {
                id: row.get(0)?,
                name: row.get(1)?,
                write_cap: row.get(2)?,
                next_index: row.get(3)?,
                created_at: row.get(4)?,
                updated_at: row.get(5)?,
            })
        }).map_err(|e| match e {
            rusqlite::Error::QueryReturnedNoRows => {
                PigeonholeDbError::ChannelNotFound(format!("id={}", id))
            }
            other => PigeonholeDbError::Database(other),
        })
    }

    pub fn list_write_channels(&self) -> Result<Vec<WriteChannel>> {
        let conn = self.conn.lock().unwrap();
        let mut stmt = conn.prepare(
            "SELECT id, name, write_cap, next_index, created_at, updated_at \
             FROM write_channels ORDER BY name",
        )?;

        let channels = stmt
            .query_map([], |row| {
                Ok(WriteChannel {
                    id: row.get(0)?,
                    name: row.get(1)?,
                    write_cap: row.get(2)?,
                    next_index: row.get(3)?,
                    created_at: row.get(4)?,
                    updated_at: row.get(5)?,
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(channels)
    }

    pub fn update_write_next_index(&self, channel_id: i64, new_index: &[u8]) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        let now = Self::now();
        conn.execute(
            "UPDATE write_channels SET next_index = ?1, updated_at = ?2 WHERE id = ?3",
            params![new_index, now, channel_id],
        )?;
        Ok(())
    }

    pub fn delete_write_channel(&self, name: &str) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        let rows = conn.execute("DELETE FROM write_channels WHERE name = ?1", params![name])?;
        if rows == 0 {
            return Err(PigeonholeDbError::ChannelNotFound(name.to_string()));
        }
        Ok(())
    }

    // ========================================================================
    // Read Channel Operations
    // ========================================================================

    pub fn create_read_channel(
        &self,
        name: &str,
        read_cap: &[u8],
        next_index: &[u8],
    ) -> Result<ReadChannel> {
        let conn = self.conn.lock().unwrap();
        let now = Self::now();

        conn.execute(
            r#"INSERT INTO read_channels (name, read_cap, next_index, created_at, updated_at)
               VALUES (?1, ?2, ?3, ?4, ?5)"#,
            params![name, read_cap, next_index, now, now],
        ).map_err(|e| match e {
            rusqlite::Error::SqliteFailure(ref err, _)
                if err.code == rusqlite::ErrorCode::ConstraintViolation =>
            {
                PigeonholeDbError::ChannelAlreadyExists(name.to_string())
            }
            other => PigeonholeDbError::Database(other),
        })?;

        let id = conn.last_insert_rowid();
        Ok(ReadChannel {
            id,
            name: name.to_string(),
            read_cap: read_cap.to_vec(),
            next_index: next_index.to_vec(),
            created_at: now,
            updated_at: now,
        })
    }

    pub fn get_read_channel(&self, name: &str) -> Result<ReadChannel> {
        let conn = self.conn.lock().unwrap();
        let mut stmt = conn.prepare(
            "SELECT id, name, read_cap, next_index, created_at, updated_at \
             FROM read_channels WHERE name = ?1",
        )?;

        stmt.query_row(params![name], |row| {
            Ok(ReadChannel {
                id: row.get(0)?,
                name: row.get(1)?,
                read_cap: row.get(2)?,
                next_index: row.get(3)?,
                created_at: row.get(4)?,
                updated_at: row.get(5)?,
            })
        }).map_err(|e| match e {
            rusqlite::Error::QueryReturnedNoRows => PigeonholeDbError::ChannelNotFound(name.to_string()),
            other => PigeonholeDbError::Database(other),
        })
    }

    pub fn get_read_channel_by_id(&self, id: i64) -> Result<ReadChannel> {
        let conn = self.conn.lock().unwrap();
        let mut stmt = conn.prepare(
            "SELECT id, name, read_cap, next_index, created_at, updated_at \
             FROM read_channels WHERE id = ?1",
        )?;

        stmt.query_row(params![id], |row| {
            Ok(ReadChannel {
                id: row.get(0)?,
                name: row.get(1)?,
                read_cap: row.get(2)?,
                next_index: row.get(3)?,
                created_at: row.get(4)?,
                updated_at: row.get(5)?,
            })
        }).map_err(|e| match e {
            rusqlite::Error::QueryReturnedNoRows => {
                PigeonholeDbError::ChannelNotFound(format!("id={}", id))
            }
            other => PigeonholeDbError::Database(other),
        })
    }

    pub fn list_read_channels(&self) -> Result<Vec<ReadChannel>> {
        let conn = self.conn.lock().unwrap();
        let mut stmt = conn.prepare(
            "SELECT id, name, read_cap, next_index, created_at, updated_at \
             FROM read_channels ORDER BY name",
        )?;

        let channels = stmt
            .query_map([], |row| {
                Ok(ReadChannel {
                    id: row.get(0)?,
                    name: row.get(1)?,
                    read_cap: row.get(2)?,
                    next_index: row.get(3)?,
                    created_at: row.get(4)?,
                    updated_at: row.get(5)?,
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(channels)
    }

    pub fn update_read_next_index(&self, channel_id: i64, new_index: &[u8]) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        let now = Self::now();
        conn.execute(
            "UPDATE read_channels SET next_index = ?1, updated_at = ?2 WHERE id = ?3",
            params![new_index, now, channel_id],
        )?;
        Ok(())
    }

    pub fn delete_read_channel(&self, name: &str) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        let rows = conn.execute("DELETE FROM read_channels WHERE name = ?1", params![name])?;
        if rows == 0 {
            return Err(PigeonholeDbError::ChannelNotFound(name.to_string()));
        }
        Ok(())
    }

    // ========================================================================
    // Pending Message Operations
    // ========================================================================

    pub fn create_pending_message(
        &self,
        write_channel_id: i64,
        plaintext: &[u8],
        message_ciphertext: &[u8],
        envelope_descriptor: &[u8],
        envelope_hash: &[u8],
        box_index: &[u8],
    ) -> Result<PendingMessage> {
        let conn = self.conn.lock().unwrap();
        let now = Self::now();

        conn.execute(
            r#"INSERT INTO pending_messages
               (write_channel_id, plaintext, message_ciphertext, envelope_descriptor, envelope_hash, box_index, attempts, status, created_at)
               VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0, 'pending', ?7)"#,
            params![write_channel_id, plaintext, message_ciphertext, envelope_descriptor, envelope_hash, box_index, now],
        )?;

        let id = conn.last_insert_rowid();
        Ok(PendingMessage {
            id,
            write_channel_id,
            plaintext: plaintext.to_vec(),
            message_ciphertext: message_ciphertext.to_vec(),
            envelope_descriptor: envelope_descriptor.to_vec(),
            envelope_hash: envelope_hash.to_vec(),
            box_index: box_index.to_vec(),
            attempts: 0,
            status: "pending".to_string(),
            created_at: now,
            last_attempt_at: None,
        })
    }

    pub fn get_pending_messages(&self, write_channel_id: i64) -> Result<Vec<PendingMessage>> {
        let conn = self.conn.lock().unwrap();
        let mut stmt = conn.prepare(
            r#"SELECT id, write_channel_id, plaintext, message_ciphertext, envelope_descriptor,
                      envelope_hash, box_index, attempts, status, created_at, last_attempt_at
               FROM pending_messages WHERE write_channel_id = ?1 ORDER BY created_at"#,
        )?;

        let messages = stmt
            .query_map(params![write_channel_id], |row| {
                Ok(PendingMessage {
                    id: row.get(0)?,
                    write_channel_id: row.get(1)?,
                    plaintext: row.get(2)?,
                    message_ciphertext: row.get(3)?,
                    envelope_descriptor: row.get(4)?,
                    envelope_hash: row.get(5)?,
                    box_index: row.get(6)?,
                    attempts: row.get(7)?,
                    status: row.get(8)?,
                    created_at: row.get(9)?,
                    last_attempt_at: row.get(10)?,
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(messages)
    }

    pub fn update_pending_message_status(&self, id: i64, status: &str) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        let now = Self::now();
        conn.execute(
            "UPDATE pending_messages SET status = ?1, attempts = attempts + 1, last_attempt_at = ?2 WHERE id = ?3",
            params![status, now, id],
        )?;
        Ok(())
    }

    pub fn delete_pending_message(&self, id: i64) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute("DELETE FROM pending_messages WHERE id = ?1", params![id])?;
        Ok(())
    }

    pub fn delete_pending_message_by_hash(&self, envelope_hash: &[u8]) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute(
            "DELETE FROM pending_messages WHERE envelope_hash = ?1",
            params![envelope_hash],
        )?;
        Ok(())
    }

    // ========================================================================
    // Received Message Operations
    // ========================================================================

    pub fn create_received_message(
        &self,
        read_channel_id: i64,
        plaintext: &[u8],
        box_index: &[u8],
    ) -> Result<ReceivedMessage> {
        let conn = self.conn.lock().unwrap();
        let now = Self::now();

        conn.execute(
            r#"INSERT INTO received_messages (read_channel_id, plaintext, box_index, received_at, is_read)
               VALUES (?1, ?2, ?3, ?4, 0)"#,
            params![read_channel_id, plaintext, box_index, now],
        )?;

        let id = conn.last_insert_rowid();
        Ok(ReceivedMessage {
            id,
            read_channel_id,
            plaintext: plaintext.to_vec(),
            box_index: box_index.to_vec(),
            received_at: now,
            is_read: false,
        })
    }

    pub fn get_unread_messages(&self, read_channel_id: i64) -> Result<Vec<ReceivedMessage>> {
        let conn = self.conn.lock().unwrap();
        let mut stmt = conn.prepare(
            r#"SELECT id, read_channel_id, plaintext, box_index, received_at, is_read
               FROM received_messages WHERE read_channel_id = ?1 AND is_read = 0 ORDER BY received_at"#,
        )?;

        let messages = stmt
            .query_map(params![read_channel_id], |row| {
                Ok(ReceivedMessage {
                    id: row.get(0)?,
                    read_channel_id: row.get(1)?,
                    plaintext: row.get(2)?,
                    box_index: row.get(3)?,
                    received_at: row.get(4)?,
                    is_read: row.get::<_, i64>(5)? != 0,
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(messages)
    }

    pub fn mark_message_read(&self, id: i64) -> Result<()> {
        let conn = self.conn.lock().unwrap();
        conn.execute(
            "UPDATE received_messages SET is_read = 1 WHERE id = ?1",
            params![id],
        )?;
        Ok(())
    }

    pub fn get_all_messages(&self, read_channel_id: i64) -> Result<Vec<ReceivedMessage>> {
        let conn = self.conn.lock().unwrap();
        let mut stmt = conn.prepare(
            r#"SELECT id, read_channel_id, plaintext, box_index, received_at, is_read
               FROM received_messages WHERE read_channel_id = ?1 ORDER BY received_at"#,
        )?;

        let messages = stmt
            .query_map(params![read_channel_id], |row| {
                Ok(ReceivedMessage {
                    id: row.get(0)?,
                    read_channel_id: row.get(1)?,
                    plaintext: row.get(2)?,
                    box_index: row.get(3)?,
                    received_at: row.get(4)?,
                    is_read: row.get::<_, i64>(5)? != 0,
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(messages)
    }
}