-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmessage.rs
More file actions
1599 lines (1412 loc) · 58.4 KB
/
message.rs
File metadata and controls
1599 lines (1412 loc) · 58.4 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
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::room_state::member::MemberId;
use crate::room_state::privacy::{PrivacyMode, SecretVersion};
use crate::room_state::ChatRoomParametersV1;
use crate::util::sign_struct;
use crate::util::{truncated_base64, verify_struct};
use crate::ChatRoomStateV1;
use ed25519_dalek::{Signature, SigningKey, VerifyingKey};
use freenet_scaffold::util::{fast_hash, FastHash};
use freenet_scaffold::ComposableState;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::time::SystemTime;
/// Computed state for message actions (edits, deletes, reactions)
/// This is rebuilt from action messages and not serialized
#[derive(Clone, PartialEq, Debug, Default)]
pub struct MessageActionsState {
/// Messages that have been edited: message_id -> new text content
pub edited_content: HashMap<MessageId, String>,
/// Messages that have been deleted
pub deleted: std::collections::HashSet<MessageId>,
/// Reactions on messages: message_id -> (emoji -> list of reactors)
pub reactions: HashMap<MessageId, HashMap<String, Vec<MemberId>>>,
}
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug, Default)]
pub struct MessagesV1 {
pub messages: Vec<AuthorizedMessageV1>,
/// Computed state from action messages (not serialized - rebuilt on each delta)
#[serde(skip)]
pub actions_state: MessageActionsState,
}
impl ComposableState for MessagesV1 {
type ParentState = ChatRoomStateV1;
type Summary = Vec<MessageId>;
type Delta = Vec<AuthorizedMessageV1>;
type Parameters = ChatRoomParametersV1;
fn verify(
&self,
parent_state: &Self::ParentState,
parameters: &Self::Parameters,
) -> Result<(), String> {
let members_by_id = parent_state.members.members_by_member_id();
let owner_id = parameters.owner_id();
for message in &self.messages {
let verifying_key = if message.message.author == owner_id {
// Owner's messages are validated against the owner's key
¶meters.owner
} else if let Some(member) = members_by_id.get(&message.message.author) {
// Regular member messages are validated against their member key
&member.member.member_vk
} else {
return Err(format!(
"Message author not found: {:?}",
message.message.author
));
};
if message.validate(verifying_key).is_err() {
return Err(format!("Invalid message signature: id:{:?}", message.id()));
}
}
Ok(())
}
fn summarize(
&self,
_parent_state: &Self::ParentState,
_parameters: &Self::Parameters,
) -> Self::Summary {
self.messages.iter().map(|m| m.id()).collect()
}
fn delta(
&self,
_parent_state: &Self::ParentState,
_parameters: &Self::Parameters,
old_state_summary: &Self::Summary,
) -> Option<Self::Delta> {
let delta: Vec<AuthorizedMessageV1> = self
.messages
.iter()
.filter(|m| !old_state_summary.contains(&m.id()))
.cloned()
.collect();
if delta.is_empty() {
None
} else {
Some(delta)
}
}
fn apply_delta(
&mut self,
parent_state: &Self::ParentState,
parameters: &Self::Parameters,
delta: &Option<Self::Delta>,
) -> Result<(), String> {
let max_recent_messages = parent_state.configuration.configuration.max_recent_messages;
let max_message_size = parent_state.configuration.configuration.max_message_size;
let privacy_mode = &parent_state.configuration.configuration.privacy_mode;
let current_secret_version = parent_state.secrets.current_version;
// Validate message constraints before adding
if let Some(delta) = delta {
for msg in delta {
let content = &msg.message.content;
match content {
RoomMessageBody::Private { secret_version, .. } => {
// In private mode, verify secret version matches current
if *privacy_mode == PrivacyMode::Private
&& *secret_version != current_secret_version
{
return Err(format!(
"Private message secret version {} does not match current version {}",
secret_version, current_secret_version
));
}
// Verify all current members have encrypted blobs for this version
let members = parent_state.members.members_by_member_id();
if !parent_state.secrets.has_complete_distribution(&members) {
return Err(
"Cannot accept private messages: incomplete secret distribution"
.to_string(),
);
}
}
RoomMessageBody::Public { .. } => {
// In private mode, reject public messages (everything must be encrypted)
// Exception: event messages (joins, etc.) contain no sensitive content
if *privacy_mode == PrivacyMode::Private && !content.is_event() {
return Err("Cannot send public messages in private room".to_string());
}
}
}
}
// Deduplicate by message ID to prevent duplicate messages from race conditions
let existing_ids: std::collections::HashSet<_> =
self.messages.iter().map(|m| m.id()).collect();
self.messages.extend(
delta
.iter()
.filter(|msg| !existing_ids.contains(&msg.id()))
.cloned(),
);
}
// Always enforce message constraints
// Ensure there are no messages over the size limit
self.messages
.retain(|m| m.message.content.content_len() <= max_message_size);
// Ensure all messages are signed by a valid member or the room owner, remove if not
let members_by_id = parent_state.members.members_by_member_id();
let owner_id = MemberId::from(¶meters.owner);
self.messages.retain(|m| {
members_by_id.contains_key(&m.message.author) || m.message.author == owner_id
});
// Sort messages by time, with MessageId as secondary sort for deterministic ordering
// (CRDT convergence requirement - without this, ties produce non-deterministic order)
self.messages.sort_by(|a, b| {
a.message
.time
.cmp(&b.message.time)
.then_with(|| a.id().cmp(&b.id()))
});
// Remove oldest messages if there are too many
if self.messages.len() > max_recent_messages {
self.messages
.drain(0..self.messages.len() - max_recent_messages);
}
// Rebuild computed state from action messages
self.rebuild_actions_state();
Ok(())
}
}
impl MessagesV1 {
/// Rebuild the computed actions state by scanning all action messages.
///
/// This method only processes PUBLIC action messages. For private rooms,
/// use `rebuild_actions_state_with_decrypted` and provide the decrypted
/// content for each private action message.
pub fn rebuild_actions_state(&mut self) {
self.rebuild_actions_state_with_decrypted(&HashMap::new());
}
/// Rebuild actions state with decrypted content for private action messages.
///
/// For private rooms, the caller should decrypt each private action message
/// and provide the plaintext bytes in `decrypted_content`, keyed by message ID.
///
/// # Arguments
/// * `decrypted_content` - Map of message_id -> decrypted plaintext bytes for
/// private action messages. Public actions are decoded directly.
pub fn rebuild_actions_state_with_decrypted(
&mut self,
decrypted_content: &HashMap<MessageId, Vec<u8>>,
) {
use crate::room_state::content::{
ActionContentV1, DecodedContent, ACTION_TYPE_DELETE, ACTION_TYPE_EDIT,
ACTION_TYPE_REACTION, ACTION_TYPE_REMOVE_REACTION,
};
// Clear existing computed state
self.actions_state = MessageActionsState::default();
// Build a map of message_id -> author for authorization checks
let message_authors: HashMap<MessageId, MemberId> = self
.messages
.iter()
.filter(|m| !m.message.content.is_action())
.map(|m| (m.id(), m.message.author))
.collect();
// Process action messages in timestamp order (messages are already sorted)
for msg in &self.messages {
let actor = msg.message.author;
// Skip non-action messages
if !msg.message.content.is_action() {
continue;
}
// Decode the action content - either from public data or decrypted bytes
let action = match &msg.message.content {
RoomMessageBody::Public { .. } => {
// Public action - decode directly
match msg.message.content.decode_content() {
Some(DecodedContent::Action(action)) => action,
_ => continue,
}
}
RoomMessageBody::Private { .. } => {
// Private action - use provided decrypted content
let msg_id = msg.id();
if let Some(plaintext) = decrypted_content.get(&msg_id) {
match ActionContentV1::decode(plaintext) {
Ok(action) => action,
Err(_) => continue,
}
} else {
// No decrypted content provided - skip this action
continue;
}
}
};
let target = &action.target;
match action.action_type {
ACTION_TYPE_EDIT => {
// Only the original author can edit their message
if let Some(&original_author) = message_authors.get(target) {
if actor == original_author {
// Don't allow editing deleted messages
if !self.actions_state.deleted.contains(target) {
if let Some(payload) = action.edit_payload() {
self.actions_state
.edited_content
.insert(target.clone(), payload.new_text);
}
}
}
}
}
ACTION_TYPE_DELETE => {
// Only the original author can delete their message
if let Some(&original_author) = message_authors.get(target) {
if actor == original_author {
self.actions_state.deleted.insert(target.clone());
// Also remove any edited content for deleted messages
self.actions_state.edited_content.remove(target);
}
}
}
ACTION_TYPE_REACTION => {
// Anyone can add reactions to non-deleted messages
if message_authors.contains_key(target)
&& !self.actions_state.deleted.contains(target)
{
if let Some(payload) = action.reaction_payload() {
let reactions = self
.actions_state
.reactions
.entry(target.clone())
.or_default();
let reactors = reactions.entry(payload.emoji).or_default();
// Idempotent: only add if not already present
if !reactors.contains(&actor) {
reactors.push(actor);
}
}
}
}
ACTION_TYPE_REMOVE_REACTION => {
// Users can only remove their own reactions
if let Some(payload) = action.reaction_payload() {
if let Some(reactions) = self.actions_state.reactions.get_mut(target) {
if let Some(reactors) = reactions.get_mut(&payload.emoji) {
reactors.retain(|r| r != &actor);
// Clean up empty entries
if reactors.is_empty() {
reactions.remove(&payload.emoji);
}
}
if reactions.is_empty() {
self.actions_state.reactions.remove(target);
}
}
}
}
_ => {
// Unknown action type - ignore for forward compatibility
}
}
}
}
/// Check if a message has been edited
pub fn is_edited(&self, message_id: &MessageId) -> bool {
self.actions_state.edited_content.contains_key(message_id)
}
/// Check if a message has been deleted
pub fn is_deleted(&self, message_id: &MessageId) -> bool {
self.actions_state.deleted.contains(message_id)
}
/// Get the effective text content for a message (edited content if edited, original otherwise)
/// Returns the text content as a string, or None if the message is encrypted/undecodable
pub fn effective_text(&self, message: &AuthorizedMessageV1) -> Option<String> {
let id = message.id();
// Check if there's edited content first
if let Some(edited_text) = self.actions_state.edited_content.get(&id) {
return Some(edited_text.clone());
}
// Otherwise return the original content's text
message.message.content.as_public_string()
}
/// Get reactions for a message
pub fn reactions(&self, message_id: &MessageId) -> Option<&HashMap<String, Vec<MemberId>>> {
self.actions_state.reactions.get(message_id)
}
/// Get all non-deleted, non-action messages for display
pub fn display_messages(&self) -> impl Iterator<Item = &AuthorizedMessageV1> {
self.messages.iter().filter(|m| {
!m.message.content.is_action() && !self.actions_state.deleted.contains(&m.id())
})
}
}
/// Message body that can be either public or private (encrypted).
///
/// Content is opaque to the contract - interpretation happens client-side.
/// This design enables adding new content types without contract redeployment.
///
/// # Content Types
/// - `content_type = 1`: Text message (TextContentV1)
/// - `content_type = 2`: Action on another message (ActionContentV1)
/// - `content_type = 3`: Reply to another message (ReplyContentV1)
/// - `content_type = 4`: Room event like join/leave (EventContentV1)
/// - Allowed as Public even in private rooms (contains no sensitive content)
/// - Old clients display as "[Unsupported message type 4.1 - please upgrade]"
/// - Future types can be added without contract changes
///
/// # Extensibility
/// - New content types: Just use a new content_type number
/// - New action types: Just use a new action_type number within ActionContentV1
/// - New fields: Add to content structs (old clients ignore unknown fields)
/// - Breaking changes: Bump content_version
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub enum RoomMessageBody {
/// Public (unencrypted) message
Public {
/// Content type identifier (see content module for constants)
content_type: u32,
/// Version of the content format
content_version: u32,
/// CBOR-encoded content bytes
data: Vec<u8>,
},
/// Private (encrypted) message
Private {
/// Content type identifier (see content module for constants)
content_type: u32,
/// Version of the content format
content_version: u32,
/// Encrypted CBOR-encoded content
ciphertext: Vec<u8>,
/// Nonce used for encryption
nonce: [u8; 12],
/// Version of the room secret used for encryption
secret_version: SecretVersion,
},
}
impl RoomMessageBody {
/// Create a new public text message
pub fn public(text: String) -> Self {
use crate::room_state::content::{TextContentV1, CONTENT_TYPE_TEXT, TEXT_CONTENT_VERSION};
let content = TextContentV1::new(text);
Self::Public {
content_type: CONTENT_TYPE_TEXT,
content_version: TEXT_CONTENT_VERSION,
data: content.encode(),
}
}
/// Create a join event message
pub fn join_event() -> Self {
use crate::room_state::content::{
EventContentV1, CONTENT_TYPE_EVENT, EVENT_CONTENT_VERSION,
};
let content = EventContentV1::join();
Self::Public {
content_type: CONTENT_TYPE_EVENT,
content_version: EVENT_CONTENT_VERSION,
data: content.encode(),
}
}
/// Create a new public message with raw content
pub fn public_raw(content_type: u32, content_version: u32, data: Vec<u8>) -> Self {
Self::Public {
content_type,
content_version,
data,
}
}
/// Create a new private message
pub fn private(
content_type: u32,
content_version: u32,
ciphertext: Vec<u8>,
nonce: [u8; 12],
secret_version: SecretVersion,
) -> Self {
Self::Private {
content_type,
content_version,
ciphertext,
nonce,
secret_version,
}
}
/// Create a private text message (convenience method)
pub fn private_text(
ciphertext: Vec<u8>,
nonce: [u8; 12],
secret_version: SecretVersion,
) -> Self {
use crate::room_state::content::{CONTENT_TYPE_TEXT, TEXT_CONTENT_VERSION};
Self::Private {
content_type: CONTENT_TYPE_TEXT,
content_version: TEXT_CONTENT_VERSION,
ciphertext,
nonce,
secret_version,
}
}
/// Create an edit action (public)
pub fn edit(target: MessageId, new_text: String) -> Self {
use crate::room_state::content::{
ActionContentV1, ACTION_CONTENT_VERSION, CONTENT_TYPE_ACTION,
};
let action = ActionContentV1::edit(target, new_text);
Self::Public {
content_type: CONTENT_TYPE_ACTION,
content_version: ACTION_CONTENT_VERSION,
data: action.encode(),
}
}
/// Create a delete action (public)
pub fn delete(target: MessageId) -> Self {
use crate::room_state::content::{
ActionContentV1, ACTION_CONTENT_VERSION, CONTENT_TYPE_ACTION,
};
let action = ActionContentV1::delete(target);
Self::Public {
content_type: CONTENT_TYPE_ACTION,
content_version: ACTION_CONTENT_VERSION,
data: action.encode(),
}
}
/// Create a reaction action (public)
pub fn reaction(target: MessageId, emoji: String) -> Self {
use crate::room_state::content::{
ActionContentV1, ACTION_CONTENT_VERSION, CONTENT_TYPE_ACTION,
};
let action = ActionContentV1::reaction(target, emoji);
Self::Public {
content_type: CONTENT_TYPE_ACTION,
content_version: ACTION_CONTENT_VERSION,
data: action.encode(),
}
}
/// Create a remove reaction action (public)
pub fn remove_reaction(target: MessageId, emoji: String) -> Self {
use crate::room_state::content::{
ActionContentV1, ACTION_CONTENT_VERSION, CONTENT_TYPE_ACTION,
};
let action = ActionContentV1::remove_reaction(target, emoji);
Self::Public {
content_type: CONTENT_TYPE_ACTION,
content_version: ACTION_CONTENT_VERSION,
data: action.encode(),
}
}
/// Create a public reply message
pub fn reply(
text: String,
target_message_id: MessageId,
target_author_name: String,
target_content_preview: String,
) -> Self {
use crate::room_state::content::{
ReplyContentV1, CONTENT_TYPE_REPLY, REPLY_CONTENT_VERSION,
};
let reply = ReplyContentV1::new(
text,
target_message_id,
target_author_name,
target_content_preview,
);
Self::Public {
content_type: CONTENT_TYPE_REPLY,
content_version: REPLY_CONTENT_VERSION,
data: reply.encode(),
}
}
/// Create a private action message (encrypted)
///
/// Use this for any action (edit, delete, reaction, remove_reaction) in a private room.
/// The caller should:
/// 1. Create the ActionContentV1 (e.g., `ActionContentV1::edit(target, new_text)`)
/// 2. Encode it: `action.encode()`
/// 3. Encrypt the bytes with the room secret
/// 4. Pass the ciphertext here
pub fn private_action(
ciphertext: Vec<u8>,
nonce: [u8; 12],
secret_version: SecretVersion,
) -> Self {
use crate::room_state::content::{ACTION_CONTENT_VERSION, CONTENT_TYPE_ACTION};
Self::Private {
content_type: CONTENT_TYPE_ACTION,
content_version: ACTION_CONTENT_VERSION,
ciphertext,
nonce,
secret_version,
}
}
/// Check if this is a public message
pub fn is_public(&self) -> bool {
matches!(self, Self::Public { .. })
}
/// Check if this is a private message
pub fn is_private(&self) -> bool {
matches!(self, Self::Private { .. })
}
/// Get the content type
pub fn content_type(&self) -> u32 {
match self {
Self::Public { content_type, .. } | Self::Private { content_type, .. } => *content_type,
}
}
/// Get the content version
pub fn content_version(&self) -> u32 {
match self {
Self::Public {
content_version, ..
}
| Self::Private {
content_version, ..
} => *content_version,
}
}
/// Check if this is an action message (content_type = ACTION)
pub fn is_action(&self) -> bool {
use crate::room_state::content::CONTENT_TYPE_ACTION;
self.content_type() == CONTENT_TYPE_ACTION
}
/// Check if this is an event message (content_type = EVENT)
pub fn is_event(&self) -> bool {
use crate::room_state::content::CONTENT_TYPE_EVENT;
self.content_type() == CONTENT_TYPE_EVENT
}
/// Decode the content (for public messages only)
/// Returns None for private messages - decrypt first
pub fn decode_content(&self) -> Option<crate::room_state::content::DecodedContent> {
use crate::room_state::content::{
ActionContentV1, DecodedContent, EventContentV1, ReplyContentV1, TextContentV1,
CONTENT_TYPE_ACTION, CONTENT_TYPE_EVENT, CONTENT_TYPE_REPLY, CONTENT_TYPE_TEXT,
};
match self {
Self::Public {
content_type,
content_version,
data,
} => match *content_type {
CONTENT_TYPE_TEXT => TextContentV1::decode(data).ok().map(DecodedContent::Text),
CONTENT_TYPE_ACTION => ActionContentV1::decode(data)
.ok()
.map(DecodedContent::Action),
CONTENT_TYPE_REPLY => ReplyContentV1::decode(data).ok().map(DecodedContent::Reply),
CONTENT_TYPE_EVENT => EventContentV1::decode(data).ok().map(DecodedContent::Event),
_ => Some(DecodedContent::Unknown {
content_type: *content_type,
content_version: *content_version,
}),
},
Self::Private { .. } => None,
}
}
/// Get the target message ID if this is an action
pub fn target_id(&self) -> Option<MessageId> {
use crate::room_state::content::{ActionContentV1, CONTENT_TYPE_ACTION};
match self {
Self::Public {
content_type, data, ..
} if *content_type == CONTENT_TYPE_ACTION => {
ActionContentV1::decode(data).ok().map(|a| a.target)
}
_ => None,
}
}
/// Get the content length for validation (contract uses this for size limits)
pub fn content_len(&self) -> usize {
match self {
Self::Public { data, .. } => data.len(),
Self::Private { ciphertext, .. } => ciphertext.len(),
}
}
/// Get the secret version (if private)
pub fn secret_version(&self) -> Option<SecretVersion> {
match self {
Self::Public { .. } => None,
Self::Private { secret_version, .. } => Some(*secret_version),
}
}
/// Get a string representation for display purposes
pub fn to_string_lossy(&self) -> String {
match self {
Self::Public { .. } => {
if let Some(decoded) = self.decode_content() {
decoded.to_display_string()
} else {
"[Failed to decode message]".to_string()
}
}
Self::Private {
ciphertext,
secret_version,
..
} => {
format!(
"[Encrypted message: {} bytes, v{}]",
ciphertext.len(),
secret_version
)
}
}
}
/// Try to get the public plaintext, returns None if private or not a text message
pub fn as_public_string(&self) -> Option<String> {
self.decode_content()
.and_then(|c| c.as_text().map(|s| s.to_string()))
}
}
impl fmt::Display for RoomMessageBody {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.to_string_lossy())
}
}
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
pub struct MessageV1 {
pub room_owner: MemberId,
pub author: MemberId,
pub time: SystemTime,
pub content: RoomMessageBody,
}
impl Default for MessageV1 {
fn default() -> Self {
Self {
room_owner: MemberId(FastHash(0)),
author: MemberId(FastHash(0)),
time: SystemTime::UNIX_EPOCH,
content: RoomMessageBody::public(String::new()),
}
}
}
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct AuthorizedMessageV1 {
pub message: MessageV1,
pub signature: Signature,
}
impl fmt::Debug for AuthorizedMessageV1 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AuthorizedMessage")
.field("message", &self.message)
.field(
"signature",
&format_args!("{}", truncated_base64(self.signature.to_bytes())),
)
.finish()
}
}
#[derive(Eq, PartialEq, Hash, Serialize, Deserialize, Clone, Debug, Ord, PartialOrd)]
pub struct MessageId(pub FastHash);
impl fmt::Display for MessageId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.0)
}
}
impl AuthorizedMessageV1 {
pub fn new(message: MessageV1, signing_key: &SigningKey) -> Self {
Self {
message: message.clone(),
signature: sign_struct(&message, signing_key),
}
}
/// Create an AuthorizedMessageV1 with a pre-computed signature.
/// Use this when signing is done externally (e.g., via delegate).
pub fn with_signature(message: MessageV1, signature: Signature) -> Self {
Self { message, signature }
}
pub fn validate(
&self,
verifying_key: &VerifyingKey,
) -> Result<(), ed25519_dalek::SignatureError> {
verify_struct(&self.message, &self.signature, verifying_key)
}
pub fn id(&self) -> MessageId {
MessageId(fast_hash(&self.signature.to_bytes()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ed25519_dalek::{Signer, SigningKey};
use rand::rngs::OsRng;
use std::time::Duration;
fn create_test_message(owner_id: MemberId, author_id: MemberId) -> MessageV1 {
MessageV1 {
room_owner: owner_id,
author: author_id,
time: SystemTime::now(),
content: RoomMessageBody::public("Test message".to_string()),
}
}
#[test]
fn test_messages_v1_default() {
let default_messages = MessagesV1::default();
assert!(default_messages.messages.is_empty());
}
#[test]
fn test_authorized_message_v1_debug() {
let signing_key = SigningKey::generate(&mut OsRng);
let owner_id = MemberId(FastHash(0));
let author_id = MemberId(FastHash(1));
let message = create_test_message(owner_id, author_id);
let authorized_message = AuthorizedMessageV1::new(message, &signing_key);
let debug_output = format!("{:?}", authorized_message);
assert!(debug_output.contains("AuthorizedMessage"));
assert!(debug_output.contains("message"));
assert!(debug_output.contains("signature"));
}
#[test]
fn test_authorized_message_new_and_validate() {
let signing_key = SigningKey::generate(&mut OsRng);
let verifying_key = signing_key.verifying_key();
let owner_id = MemberId(FastHash(0));
let author_id = MemberId(FastHash(1));
let message = create_test_message(owner_id, author_id);
let authorized_message = AuthorizedMessageV1::new(message.clone(), &signing_key);
assert_eq!(authorized_message.message, message);
assert!(authorized_message.validate(&verifying_key).is_ok());
// Test with wrong key
let wrong_key = SigningKey::generate(&mut OsRng).verifying_key();
assert!(authorized_message.validate(&wrong_key).is_err());
// Test with tampered message
let mut tampered_message = authorized_message.clone();
tampered_message.message.content = RoomMessageBody::public("Tampered content".to_string());
assert!(tampered_message.validate(&verifying_key).is_err());
}
#[test]
fn test_message_id() {
let signing_key = SigningKey::generate(&mut OsRng);
let owner_id = MemberId(FastHash(0));
let author_id = MemberId(FastHash(1));
let message = create_test_message(owner_id, author_id);
let authorized_message = AuthorizedMessageV1::new(message, &signing_key);
let id1 = authorized_message.id();
let id2 = authorized_message.id();
assert_eq!(id1, id2);
// Test that different messages have different IDs
let message2 = create_test_message(owner_id, author_id);
let authorized_message2 = AuthorizedMessageV1::new(message2, &signing_key);
assert_ne!(authorized_message.id(), authorized_message2.id());
}
#[test]
fn test_messages_verify() {
// Generate a new signing key and its corresponding verifying key for the owner
let owner_signing_key = SigningKey::generate(&mut OsRng);
let owner_verifying_key = owner_signing_key.verifying_key();
let owner_id = MemberId::from(&owner_verifying_key);
// Generate a signing key for the author
let author_signing_key = SigningKey::generate(&mut OsRng);
let author_verifying_key = author_signing_key.verifying_key();
let author_id = MemberId::from(&author_verifying_key);
// Create a test message and authorize it with the author's signing key
let message = create_test_message(owner_id, author_id);
let authorized_message = AuthorizedMessageV1::new(message, &author_signing_key);
// Create a Messages struct with the authorized message
let messages = MessagesV1 {
messages: vec![authorized_message],
..Default::default()
};
// Set up a parent room_state (ChatRoomState) with the author as a member
let mut parent_state = ChatRoomStateV1::default();
let author_member = crate::room_state::member::Member {
owner_member_id: owner_id,
invited_by: owner_id,
member_vk: author_verifying_key,
};
let authorized_author =
crate::room_state::member::AuthorizedMember::new(author_member, &owner_signing_key);
parent_state.members.members = vec![authorized_author];
// Set up parameters for verification
let parameters = ChatRoomParametersV1 {
owner: owner_verifying_key,
};
// Verify that a valid message passes verification
assert!(
messages.verify(&parent_state, ¶meters).is_ok(),
"Valid messages should pass verification: {:?}",
messages.verify(&parent_state, ¶meters)
);
// Test with invalid signature
let mut invalid_messages = messages.clone();
invalid_messages.messages[0].signature = Signature::from_bytes(&[0; 64]); // Replace with an invalid signature
assert!(
invalid_messages.verify(&parent_state, ¶meters).is_err(),
"Messages with invalid signature should fail verification"
);
// Test with non-existent author
let non_existent_author_id =
MemberId::from(&SigningKey::generate(&mut OsRng).verifying_key());
let invalid_message = create_test_message(owner_id, non_existent_author_id);
let invalid_authorized_message =
AuthorizedMessageV1::new(invalid_message, &author_signing_key);
let invalid_messages = MessagesV1 {
messages: vec![invalid_authorized_message],
..Default::default()
};
assert!(
invalid_messages.verify(&parent_state, ¶meters).is_err(),
"Messages with non-existent author should fail verification"
);
}
#[test]
fn test_messages_summarize() {
let signing_key = SigningKey::generate(&mut OsRng);
let owner_id = MemberId(FastHash(0));
let author_id = MemberId(FastHash(1));
let message1 = create_test_message(owner_id, author_id);
let message2 = create_test_message(owner_id, author_id);
let authorized_message1 = AuthorizedMessageV1::new(message1, &signing_key);
let authorized_message2 = AuthorizedMessageV1::new(message2, &signing_key);
let messages = MessagesV1 {
messages: vec![authorized_message1.clone(), authorized_message2.clone()],
..Default::default()
};
let parent_state = ChatRoomStateV1::default();
let parameters = ChatRoomParametersV1 {
owner: signing_key.verifying_key(),
};
let summary = messages.summarize(&parent_state, ¶meters);
assert_eq!(summary.len(), 2);
assert_eq!(summary[0], authorized_message1.id());
assert_eq!(summary[1], authorized_message2.id());
// Test empty messages
let empty_messages = MessagesV1::default();
let empty_summary = empty_messages.summarize(&parent_state, ¶meters);
assert!(empty_summary.is_empty());
}
#[test]
fn test_messages_delta() {
let signing_key = SigningKey::generate(&mut OsRng);
let owner_id = MemberId(FastHash(0));
let author_id = MemberId(FastHash(1));
// Use distinct timestamps to ensure unique message IDs
let base = SystemTime::now();
let message1 = MessageV1 {
room_owner: owner_id,
author: author_id,
time: base,
content: RoomMessageBody::public("Message 1".to_string()),
};
let message2 = MessageV1 {
room_owner: owner_id,
author: author_id,
time: base + Duration::from_millis(1),
content: RoomMessageBody::public("Message 2".to_string()),
};
let message3 = MessageV1 {
room_owner: owner_id,
author: author_id,
time: base + Duration::from_millis(2),
content: RoomMessageBody::public("Message 3".to_string()),
};
let authorized_message1 = AuthorizedMessageV1::new(message1, &signing_key);
let authorized_message2 = AuthorizedMessageV1::new(message2, &signing_key);
let authorized_message3 = AuthorizedMessageV1::new(message3, &signing_key);
let messages = MessagesV1 {
messages: vec![
authorized_message1.clone(),
authorized_message2.clone(),