2026-02-06 23:58:23 +07:00
|
|
|
use std::rc::Rc;
|
2025-12-22 09:40:46 -08:00
|
|
|
|
2026-02-27 14:32:47 +08:00
|
|
|
use storage::StorageConfig;
|
|
|
|
|
|
2026-01-22 06:39:09 +07:00
|
|
|
use crate::{
|
2026-02-06 23:41:12 +07:00
|
|
|
conversation::{ConversationId, ConversationStore, Convo, Id},
|
2026-01-29 00:59:07 +07:00
|
|
|
errors::ChatError,
|
2026-01-22 06:39:09 +07:00
|
|
|
identity::Identity,
|
|
|
|
|
inbox::Inbox,
|
2026-02-06 23:41:12 +07:00
|
|
|
proto::{EncryptedPayload, EnvelopeV1, Message},
|
2026-02-27 15:31:38 +08:00
|
|
|
storage::ChatStorage,
|
2026-01-29 23:36:18 +07:00
|
|
|
types::{AddressedEnvelope, ContentData},
|
2026-01-22 06:39:09 +07:00
|
|
|
};
|
2025-12-22 09:40:46 -08:00
|
|
|
|
2026-02-06 23:58:23 +07:00
|
|
|
pub use crate::conversation::ConversationIdOwned;
|
2026-01-26 23:53:44 +07:00
|
|
|
pub use crate::inbox::Introduction;
|
2026-01-29 00:59:07 +07:00
|
|
|
|
2026-01-22 06:39:09 +07:00
|
|
|
// This is the main entry point to the conversations api.
|
|
|
|
|
// Ctx manages lifetimes of objects to process and generate payloads.
|
|
|
|
|
pub struct Context {
|
|
|
|
|
_identity: Rc<Identity>,
|
2025-12-22 09:40:46 -08:00
|
|
|
store: ConversationStore,
|
2026-01-22 06:39:09 +07:00
|
|
|
inbox: Inbox,
|
2026-02-27 14:32:47 +08:00
|
|
|
storage: ChatStorage,
|
2025-12-22 09:40:46 -08:00
|
|
|
}
|
|
|
|
|
|
2026-01-22 06:39:09 +07:00
|
|
|
impl Context {
|
2026-02-27 14:32:47 +08:00
|
|
|
/// Opens or creates a Context with the given storage configuration.
|
|
|
|
|
///
|
|
|
|
|
/// If an identity exists in storage, it will be restored.
|
|
|
|
|
/// Otherwise, a new identity will be created with the given name and saved.
|
2026-02-27 15:31:38 +08:00
|
|
|
pub fn open(name: impl Into<String>, config: StorageConfig) -> Result<Self, ChatError> {
|
2026-02-27 14:32:47 +08:00
|
|
|
let mut storage = ChatStorage::new(config)?;
|
|
|
|
|
let name = name.into();
|
|
|
|
|
|
|
|
|
|
// Load or create identity
|
|
|
|
|
let identity = if let Some(identity) = storage.load_identity()? {
|
|
|
|
|
identity
|
|
|
|
|
} else {
|
|
|
|
|
let identity = Identity::new(&name);
|
|
|
|
|
storage.save_identity(&identity)?;
|
|
|
|
|
identity
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let identity = Rc::new(identity);
|
2026-03-12 16:22:51 +08:00
|
|
|
let inbox = Inbox::new(Rc::clone(&identity));
|
2026-02-27 14:32:47 +08:00
|
|
|
|
|
|
|
|
Ok(Self {
|
2026-01-22 06:39:09 +07:00
|
|
|
_identity: identity,
|
2025-12-22 09:40:46 -08:00
|
|
|
store: ConversationStore::new(),
|
2026-01-22 06:39:09 +07:00
|
|
|
inbox,
|
2026-02-27 14:32:47 +08:00
|
|
|
storage,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Creates a new in-memory Context (for testing).
|
|
|
|
|
///
|
|
|
|
|
/// Uses in-memory SQLite database. Each call creates a new isolated database.
|
|
|
|
|
pub fn new_with_name(name: impl Into<String>) -> Self {
|
|
|
|
|
Self::open(name, StorageConfig::InMemory).expect("in-memory storage should not fail")
|
2025-12-22 09:40:46 -08:00
|
|
|
}
|
|
|
|
|
|
2026-02-19 17:25:42 -08:00
|
|
|
pub fn installation_name(&self) -> &str {
|
|
|
|
|
self._identity.get_name()
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-22 06:39:09 +07:00
|
|
|
pub fn create_private_convo(
|
|
|
|
|
&mut self,
|
2026-01-26 23:53:44 +07:00
|
|
|
remote_bundle: &Introduction,
|
2026-02-06 23:08:06 +07:00
|
|
|
content: &[u8],
|
2026-02-06 23:58:23 +07:00
|
|
|
) -> (ConversationIdOwned, Vec<AddressedEnvelope>) {
|
2026-01-26 23:53:44 +07:00
|
|
|
let (convo, payloads) = self
|
2026-01-22 06:39:09 +07:00
|
|
|
.inbox
|
|
|
|
|
.invite_to_private_convo(remote_bundle, content)
|
|
|
|
|
.unwrap_or_else(|_| todo!("Log/Surface Error"));
|
|
|
|
|
|
2026-02-11 19:51:22 +01:00
|
|
|
let remote_id = Inbox::inbox_identifier_for_key(*remote_bundle.installation_key());
|
2026-01-29 23:36:18 +07:00
|
|
|
let payload_bytes = payloads
|
|
|
|
|
.into_iter()
|
2026-02-10 18:34:33 +01:00
|
|
|
.map(|p| p.into_envelope(remote_id.clone()))
|
2026-01-29 23:36:18 +07:00
|
|
|
.collect();
|
|
|
|
|
|
2026-02-06 23:58:23 +07:00
|
|
|
let convo_id = self.add_convo(Box::new(convo));
|
|
|
|
|
(convo_id, payload_bytes)
|
2025-12-22 09:40:46 -08:00
|
|
|
}
|
|
|
|
|
|
2026-02-28 03:16:10 -08:00
|
|
|
pub fn list_conversations(&self) -> Result<Vec<ConversationIdOwned>, ChatError> {
|
|
|
|
|
Ok(self.store.conversation_ids())
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-29 23:36:18 +07:00
|
|
|
pub fn send_content(
|
|
|
|
|
&mut self,
|
2026-02-06 23:58:23 +07:00
|
|
|
convo_id: ConversationId,
|
2026-01-29 23:36:18 +07:00
|
|
|
content: &[u8],
|
|
|
|
|
) -> Result<Vec<AddressedEnvelope>, ChatError> {
|
2026-02-06 23:58:23 +07:00
|
|
|
// Lookup convo by id
|
|
|
|
|
let convo = self.get_convo_mut(convo_id)?;
|
2026-01-29 23:36:18 +07:00
|
|
|
|
|
|
|
|
// Generate encrypted payloads
|
|
|
|
|
let payloads = convo.send_message(content)?;
|
|
|
|
|
|
|
|
|
|
// Attach conversation_ids to Envelopes
|
|
|
|
|
Ok(payloads
|
|
|
|
|
.into_iter()
|
2026-02-10 18:34:33 +01:00
|
|
|
.map(|p| p.into_envelope(convo.remote_id()))
|
2026-01-29 23:36:18 +07:00
|
|
|
.collect())
|
2025-12-22 09:40:46 -08:00
|
|
|
}
|
|
|
|
|
|
2026-02-06 23:41:12 +07:00
|
|
|
// Decode bytes and send to protocol for processing.
|
|
|
|
|
pub fn handle_payload(&mut self, payload: &[u8]) -> Result<Option<ContentData>, ChatError> {
|
2026-02-10 18:34:33 +01:00
|
|
|
let env = EnvelopeV1::decode(payload)?;
|
2026-02-06 23:41:12 +07:00
|
|
|
|
|
|
|
|
// TODO: Impl Conversation hinting
|
|
|
|
|
let convo_id = env.conversation_hint;
|
2026-02-09 09:55:58 -08:00
|
|
|
let enc = EncryptedPayload::decode(env.payload)?;
|
2026-02-06 23:41:12 +07:00
|
|
|
match convo_id {
|
|
|
|
|
c if c == self.inbox.id() => self.dispatch_to_inbox(enc),
|
|
|
|
|
c if self.store.has(&c) => self.dispatch_to_convo(&c, enc),
|
2026-02-11 14:10:21 -08:00
|
|
|
_ => Ok(None),
|
2026-02-06 23:41:12 +07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Dispatch encrypted payload to Inbox, and register the created Conversation
|
|
|
|
|
fn dispatch_to_inbox(
|
|
|
|
|
&mut self,
|
|
|
|
|
enc_payload: EncryptedPayload,
|
|
|
|
|
) -> Result<Option<ContentData>, ChatError> {
|
2026-03-12 16:22:51 +08:00
|
|
|
// Look up the ephemeral key from storage
|
|
|
|
|
let key_hex = Inbox::extract_ephemeral_key_hex(&enc_payload)?;
|
|
|
|
|
let ephemeral_key = self
|
|
|
|
|
.storage
|
|
|
|
|
.load_ephemeral_key(&key_hex)?
|
|
|
|
|
.ok_or(ChatError::UnknownEphemeralKey())?;
|
|
|
|
|
|
|
|
|
|
let (convo, content) = self.inbox.handle_frame(&ephemeral_key, enc_payload)?;
|
|
|
|
|
|
|
|
|
|
// Remove consumed ephemeral key from storage
|
|
|
|
|
self.storage.remove_ephemeral_key(&key_hex)?;
|
|
|
|
|
|
2026-02-06 23:41:12 +07:00
|
|
|
self.add_convo(convo);
|
|
|
|
|
Ok(content)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Dispatch encrypted payload to its corresponding conversation
|
|
|
|
|
fn dispatch_to_convo(
|
|
|
|
|
&mut self,
|
|
|
|
|
convo_id: ConversationId,
|
|
|
|
|
enc_payload: EncryptedPayload,
|
|
|
|
|
) -> Result<Option<ContentData>, ChatError> {
|
2026-02-10 18:34:33 +01:00
|
|
|
let Some(convo) = self.store.get_mut(convo_id) else {
|
2026-02-06 23:41:12 +07:00
|
|
|
return Err(ChatError::Protocol("convo id not found".into()));
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
convo.handle_frame(enc_payload)
|
2025-12-22 09:40:46 -08:00
|
|
|
}
|
2026-01-29 00:59:07 +07:00
|
|
|
|
|
|
|
|
pub fn create_intro_bundle(&mut self) -> Result<Vec<u8>, ChatError> {
|
2026-03-05 20:45:18 +08:00
|
|
|
let (intro, public_key_hex, private_key) = self.inbox.create_intro_bundle();
|
|
|
|
|
self.storage
|
|
|
|
|
.save_ephemeral_key(&public_key_hex, &private_key)?;
|
|
|
|
|
Ok(intro.into())
|
2026-01-29 00:59:07 +07:00
|
|
|
}
|
|
|
|
|
|
2026-02-06 23:58:23 +07:00
|
|
|
fn add_convo(&mut self, convo: Box<dyn Convo>) -> ConversationIdOwned {
|
2026-03-13 10:15:06 +08:00
|
|
|
// Persist conversation metadata to storage
|
|
|
|
|
let _ = self.storage.save_conversation(
|
|
|
|
|
convo.id(),
|
|
|
|
|
&convo.remote_id(),
|
|
|
|
|
convo.convo_type(),
|
|
|
|
|
);
|
2026-02-10 18:34:33 +01:00
|
|
|
self.store.insert_convo(convo)
|
2026-01-29 00:59:07 +07:00
|
|
|
}
|
2026-01-29 23:36:18 +07:00
|
|
|
|
2026-02-06 23:58:23 +07:00
|
|
|
// Returns a mutable reference to a Convo for a given ConvoId
|
|
|
|
|
fn get_convo_mut(&mut self, convo_id: ConversationId) -> Result<&mut dyn Convo, ChatError> {
|
2026-01-29 23:36:18 +07:00
|
|
|
self.store
|
2026-02-10 18:34:33 +01:00
|
|
|
.get_mut(convo_id)
|
2026-02-06 23:58:23 +07:00
|
|
|
.ok_or_else(|| ChatError::NoConvo(convo_id.into()))
|
2026-01-29 23:36:18 +07:00
|
|
|
}
|
2025-12-22 09:40:46 -08:00
|
|
|
}
|
2026-01-22 06:39:09 +07:00
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
|
mod tests {
|
|
|
|
|
use super::*;
|
|
|
|
|
use crate::conversation::GroupTestConvo;
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn convo_store_get() {
|
|
|
|
|
let mut store: ConversationStore = ConversationStore::new();
|
|
|
|
|
|
|
|
|
|
let new_convo = GroupTestConvo::new();
|
2026-02-06 23:41:12 +07:00
|
|
|
let convo_id = store.insert_convo(Box::new(new_convo));
|
2026-01-22 06:39:09 +07:00
|
|
|
|
2026-02-10 18:34:33 +01:00
|
|
|
let convo = store.get_mut(&convo_id).ok_or(0);
|
2026-01-22 06:39:09 +07:00
|
|
|
convo.unwrap();
|
|
|
|
|
}
|
2026-02-11 14:10:21 -08:00
|
|
|
|
|
|
|
|
fn send_and_verify(
|
|
|
|
|
sender: &mut Context,
|
|
|
|
|
receiver: &mut Context,
|
|
|
|
|
convo_id: ConversationId,
|
|
|
|
|
content: &[u8],
|
|
|
|
|
) {
|
|
|
|
|
let payloads = sender.send_content(convo_id, content).unwrap();
|
|
|
|
|
let payload = payloads.first().unwrap();
|
|
|
|
|
let received = receiver
|
|
|
|
|
.handle_payload(&payload.data)
|
|
|
|
|
.unwrap()
|
|
|
|
|
.expect("expected content");
|
|
|
|
|
assert_eq!(content, received.data.as_slice());
|
|
|
|
|
assert!(!received.is_new_convo); // Check that `is_new_convo` is FALSE
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn ctx_integration() {
|
2026-02-19 17:25:42 -08:00
|
|
|
let mut saro = Context::new_with_name("saro");
|
|
|
|
|
let mut raya = Context::new_with_name("raya");
|
2026-02-11 14:10:21 -08:00
|
|
|
|
|
|
|
|
// Raya creates intro bundle and sends to Saro
|
|
|
|
|
let bundle = raya.create_intro_bundle().unwrap();
|
|
|
|
|
let intro = Introduction::try_from(bundle.as_slice()).unwrap();
|
|
|
|
|
|
|
|
|
|
// Saro initiates conversation with Raya
|
|
|
|
|
let mut content = vec![10];
|
|
|
|
|
let (saro_convo_id, payloads) = saro.create_private_convo(&intro, &content);
|
|
|
|
|
|
|
|
|
|
// Raya receives initial message
|
|
|
|
|
let payload = payloads.first().unwrap();
|
|
|
|
|
let initial_content = raya
|
|
|
|
|
.handle_payload(&payload.data)
|
|
|
|
|
.unwrap()
|
|
|
|
|
.expect("expected initial content");
|
|
|
|
|
|
|
|
|
|
let raya_convo_id = initial_content.conversation_id;
|
|
|
|
|
assert_eq!(content, initial_content.data);
|
|
|
|
|
assert!(initial_content.is_new_convo);
|
|
|
|
|
|
|
|
|
|
// Exchange messages back and forth
|
|
|
|
|
for _ in 0..10 {
|
|
|
|
|
content.push(content.last().unwrap() + 1);
|
|
|
|
|
send_and_verify(&mut raya, &mut saro, &raya_convo_id, &content);
|
|
|
|
|
|
|
|
|
|
content.push(content.last().unwrap() + 1);
|
|
|
|
|
send_and_verify(&mut saro, &mut raya, &saro_convo_id, &content);
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-02-27 14:32:47 +08:00
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn identity_persistence() {
|
|
|
|
|
// Use file-based storage to test real persistence
|
|
|
|
|
let dir = tempfile::tempdir().unwrap();
|
|
|
|
|
let db_path = dir
|
|
|
|
|
.path()
|
|
|
|
|
.join("test_identity.db")
|
|
|
|
|
.to_string_lossy()
|
|
|
|
|
.to_string();
|
|
|
|
|
let config = StorageConfig::File(db_path);
|
|
|
|
|
|
|
|
|
|
// Create context - this should create and save a new identity
|
|
|
|
|
let ctx1 = Context::open("alice", config.clone()).unwrap();
|
|
|
|
|
let pubkey1 = ctx1._identity.public_key();
|
|
|
|
|
let name1 = ctx1.installation_name().to_string();
|
|
|
|
|
|
|
|
|
|
// Drop and reopen - should load the same identity
|
|
|
|
|
drop(ctx1);
|
|
|
|
|
let ctx2 = Context::open("alice", config).unwrap();
|
|
|
|
|
let pubkey2 = ctx2._identity.public_key();
|
|
|
|
|
let name2 = ctx2.installation_name().to_string();
|
|
|
|
|
|
|
|
|
|
// Identity should be the same
|
|
|
|
|
assert_eq!(pubkey1, pubkey2, "public key should persist");
|
|
|
|
|
assert_eq!(name1, name2, "name should persist");
|
|
|
|
|
}
|
2026-03-12 16:22:51 +08:00
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn ephemeral_key_persistence() {
|
|
|
|
|
let dir = tempfile::tempdir().unwrap();
|
|
|
|
|
let db_path = dir
|
|
|
|
|
.path()
|
|
|
|
|
.join("test_ephemeral.db")
|
|
|
|
|
.to_string_lossy()
|
|
|
|
|
.to_string();
|
|
|
|
|
let config = StorageConfig::File(db_path);
|
|
|
|
|
|
|
|
|
|
// Create context and generate an intro bundle (creates ephemeral key)
|
|
|
|
|
let mut ctx1 = Context::open("alice", config.clone()).unwrap();
|
|
|
|
|
let bundle1 = ctx1.create_intro_bundle().unwrap();
|
|
|
|
|
|
|
|
|
|
// Drop and reopen - ephemeral keys should be restored from db
|
|
|
|
|
drop(ctx1);
|
|
|
|
|
let mut ctx2 = Context::open("alice", config.clone()).unwrap();
|
|
|
|
|
|
|
|
|
|
// Use the intro bundle from before restart to start a conversation
|
|
|
|
|
let intro = Introduction::try_from(bundle1.as_slice()).unwrap();
|
|
|
|
|
let mut bob = Context::new_with_name("bob");
|
|
|
|
|
let (_, payloads) = bob.create_private_convo(&intro, b"hello after restart");
|
|
|
|
|
|
|
|
|
|
// Alice (ctx2) should be able to handle the payload using the persisted ephemeral key
|
|
|
|
|
let payload = payloads.first().unwrap();
|
|
|
|
|
let content = ctx2
|
|
|
|
|
.handle_payload(&payload.data)
|
|
|
|
|
.expect("should handle payload with persisted ephemeral key")
|
|
|
|
|
.expect("should have content");
|
|
|
|
|
assert_eq!(content.data, b"hello after restart");
|
|
|
|
|
assert!(content.is_new_convo);
|
|
|
|
|
}
|
2026-03-13 10:15:06 +08:00
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn conversation_metadata_persistence() {
|
|
|
|
|
let dir = tempfile::tempdir().unwrap();
|
|
|
|
|
let db_path = dir
|
|
|
|
|
.path()
|
|
|
|
|
.join("test_convo_meta.db")
|
|
|
|
|
.to_string_lossy()
|
|
|
|
|
.to_string();
|
|
|
|
|
let config = StorageConfig::File(db_path);
|
|
|
|
|
|
|
|
|
|
// Create context, establish a conversation
|
|
|
|
|
let mut alice = Context::open("alice", config.clone()).unwrap();
|
|
|
|
|
let mut bob = Context::new_with_name("bob");
|
|
|
|
|
|
|
|
|
|
let bundle = alice.create_intro_bundle().unwrap();
|
|
|
|
|
let intro = Introduction::try_from(bundle.as_slice()).unwrap();
|
|
|
|
|
let (_, payloads) = bob.create_private_convo(&intro, b"hi");
|
|
|
|
|
|
|
|
|
|
let payload = payloads.first().unwrap();
|
|
|
|
|
let content = alice.handle_payload(&payload.data).unwrap().unwrap();
|
|
|
|
|
assert!(content.is_new_convo);
|
|
|
|
|
|
|
|
|
|
// Verify conversation metadata was persisted
|
|
|
|
|
let convos = alice.storage.load_conversations().unwrap();
|
|
|
|
|
assert_eq!(convos.len(), 1);
|
|
|
|
|
assert_eq!(convos[0].convo_type, "private_v1");
|
|
|
|
|
assert!(!convos[0].local_convo_id.is_empty());
|
|
|
|
|
assert!(!convos[0].remote_convo_id.is_empty());
|
|
|
|
|
|
|
|
|
|
// Drop and reopen - metadata should still be there
|
|
|
|
|
drop(alice);
|
|
|
|
|
let alice2 = Context::open("alice", config).unwrap();
|
|
|
|
|
let convos = alice2.storage.load_conversations().unwrap();
|
|
|
|
|
assert_eq!(convos.len(), 1, "conversation metadata should persist");
|
|
|
|
|
}
|
2026-01-22 06:39:09 +07:00
|
|
|
}
|