whatsapp-rust 0.7.0

Rust client for WhatsApp Web
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
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
//! Poll creation, voting, and vote decryption.

use std::collections::HashMap;

use thiserror::Error;
use wacore::poll;
use wacore_binary::{Jid, JidExt};
use waproto::whatsapp as wa;

use crate::client::Client;
use crate::send::{SendError, SendResult};

pub use wacore::poll::PollVoteCiphertext;

/// Errors from poll operations (creation, voting, and vote decryption).
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum PollError {
    /// Sending the poll/vote stanza failed (embeds the send path error).
    #[error("{0}")]
    Send(#[from] SendError),
    /// The poll definition is invalid (option count, duplicate names, bad
    /// quiz index, selectable count out of range).
    #[error("invalid poll: {0}")]
    InvalidPoll(String),
    /// The client is not logged in, so the voter identity can't be resolved.
    #[error("client is not logged in")]
    NotLoggedIn,
    /// Vote decryption/encryption (HKDF/GCM) failed.
    #[error("poll vote crypto failed: {0}")]
    Crypto(#[source] anyhow::Error),
}

#[derive(Debug, Clone)]
pub struct PollOptionResult {
    pub name: String,
    pub voters: Vec<String>,
}

pub struct Polls<'a> {
    client: &'a Client,
}

impl<'a> Polls<'a> {
    pub(crate) fn new(client: &'a Client) -> Self {
        Self { client }
    }

    /// Caller needs the returned `message_secret` to decrypt votes.
    pub async fn create(
        &self,
        to: impl Into<Jid>,
        name: &str,
        options: &[String],
        selectable_count: u32,
    ) -> Result<(SendResult, Vec<u8>), PollError> {
        let to = &to.into();
        self.create_inner(to, name, options, selectable_count, None)
            .await
    }

    /// Create a quiz poll: a single-select poll with exactly one correct option.
    ///
    /// `correct_index` is the 0-based index into `options` of the right answer.
    /// Quizzes are inherently single-select (WA Web forces `selectableOptionsCount=1`),
    /// so the count is fixed at 1. Returns the `message_secret` needed to decrypt votes.
    pub async fn create_quiz(
        &self,
        to: impl Into<Jid>,
        name: &str,
        options: &[String],
        correct_index: usize,
    ) -> Result<(SendResult, Vec<u8>), PollError> {
        let to = &to.into();
        self.create_inner(to, name, options, 1, Some(correct_index))
            .await
    }

    async fn create_inner(
        &self,
        to: &Jid,
        name: &str,
        options: &[String],
        selectable_count: u32,
        correct_index: Option<usize>,
    ) -> Result<(SendResult, Vec<u8>), PollError> {
        let poll_msg = build_poll_creation_message(name, options, selectable_count, correct_index)?;

        // WA Web: v3 for single-select, v1 for multi-select (GeneratePollCreationMessageProto.js:39-41)
        let mut message = if selectable_count == 1 {
            wa::Message {
                poll_creation_message_v3: buffa::MessageField::some(poll_msg),
                ..Default::default()
            }
        } else {
            wa::Message {
                poll_creation_message: buffa::MessageField::some(poll_msg),
                ..Default::default()
            }
        };

        // WA Web generates a 32-byte random secret at poll creation time
        // (SendPollCreationMsgAction.js:158). Voters need this to derive their encryption key.
        let message_secret: Vec<u8> = {
            use rand::Rng;
            let mut secret = vec![0u8; 32];
            rand::rng().fill_bytes(&mut secret);
            secret
        };

        message.message_context_info = buffa::MessageField::some(wa::MessageContextInfo {
            message_secret: Some(message_secret.clone()),
            ..Default::default()
        });

        let result = self.client.send_message(to, message).await?;
        Ok((result, message_secret))
    }

    pub async fn vote(
        &self,
        chat_jid: impl Into<Jid>,
        poll_msg_id: &str,
        poll_creator_jid: &Jid,
        message_secret: &[u8],
        option_names: &[String],
    ) -> Result<SendResult, PollError> {
        let chat_jid = &chat_jid.into();
        let my_jid = self.client.pn().ok_or(PollError::NotLoggedIn)?;
        let my_base = my_jid.to_non_ad();

        let voter_jid = self
            .resolve_voter_jid(poll_creator_jid, &my_base, poll_msg_id)
            .await;
        let voter_jid_str = voter_jid.to_string();
        let creator_jid_str = poll_creator_jid.to_non_ad_string();

        let selected_hashes: Vec<Vec<u8>> = option_names
            .iter()
            .map(|name| poll::compute_option_hash(name).to_vec())
            .collect();

        let (enc_payload, iv) = poll::encrypt_poll_vote_with_secret(
            &selected_hashes,
            message_secret,
            poll_msg_id,
            &creator_jid_str,
            &voter_jid_str,
        )
        .map_err(PollError::Crypto)?;

        let from_me = my_base.is_same_user_as(poll_creator_jid);

        let poll_update = wa::message::PollUpdateMessage {
            poll_creation_message_key: buffa::MessageField::some(wa::MessageKey {
                remote_jid: Some(chat_jid.to_string()),
                from_me: Some(from_me),
                id: Some(poll_msg_id.to_string()),
                participant: if chat_jid.is_group() {
                    Some(poll_creator_jid.to_string())
                } else {
                    None
                },
            }),
            vote: buffa::MessageField::some(wa::message::PollEncValue {
                enc_payload: Some(enc_payload),
                enc_iv: Some(iv.to_vec()),
            }),
            // WA Web's GeneratePollVoteMessageProto never sets metadata; a Some(empty)
            // submessage emits a stray `1A 00` (tag 3) on the wire. Omit it.
            metadata: buffa::MessageField::none(),
            sender_timestamp_ms: Some(wacore::time::now_millis()),
        };

        let message = wa::Message {
            poll_update_message: buffa::MessageField::some(poll_update),
            ..Default::default()
        };

        Ok(self.client.send_message(chat_jid, message).await?)
    }

    /// The voter (self) JID keys the vote's HKDF/AAD, so it must use the poll
    /// creator's namespace, else the host derives a different key. Own LID for
    /// LID-addressed polls, own PN otherwise, falling back to PN when our LID
    /// isn't known yet. Matches WA Web `WAWebAddonEncryption`.
    async fn resolve_voter_jid(
        &self,
        poll_creator_jid: &Jid,
        own_pn: &Jid,
        poll_msg_id: &str,
    ) -> Jid {
        if !poll_creator_jid.is_lid() {
            return own_pn.clone();
        }
        match self.client.lid() {
            Some(lid) => lid.to_non_ad(),
            None => {
                log::warn!(
                    "Poll {poll_msg_id} is LID-addressed but own LID is unknown; \
                     falling back to PN voter (host may fail to decrypt)"
                );
                own_pn.clone()
            }
        }
    }

    /// Selected option hashes (32 bytes each). Retries under the opposite
    /// namespace (LID/PN) when a counterpart is known, so votes authored across
    /// the LID migration still open. Mirrors WA Web `WAWebAddonEncryption`.
    pub async fn decrypt_vote(
        &self,
        ciphertext: PollVoteCiphertext<'_>,
        message_secret: &[u8],
        poll_msg_id: &str,
        poll_creator_jid: &Jid,
        voter_jid: &Jid,
    ) -> Result<Vec<Vec<u8>>, PollError> {
        let creator = poll_creator_jid.to_non_ad();
        let voter = voter_jid.to_non_ad();
        let creator_str = creator.to_string();
        let voter_str = voter.to_string();

        let creator_alt = self.swapped_user(&creator).await;
        let voter_alt = self.swapped_user(&voter).await;
        let fallback = Self::build_fallback(&creator_alt, &voter_alt);

        poll::decrypt_poll_vote_with_fallback(
            ciphertext,
            message_secret,
            poll_msg_id,
            poll::PollVoteAddressing {
                poll_creator_jid: &creator_str,
                voter_jid: &voter_str,
            },
            fallback,
        )
        .map_err(PollError::Crypto)
    }

    /// Non-AD LID/PN counterpart of a user JID, or `None` when unmapped.
    async fn swapped_user(&self, jid: &Jid) -> Option<String> {
        self.client
            .swap_pn_lid_namespace(jid)
            .await
            .map(|j| j.to_non_ad_string())
    }

    /// Fallback pair only when both JIDs have a counterpart, keeping it
    /// homogeneous (LID or PN, never mixed) like WA Web's `decryptAddOn`.
    fn build_fallback<'b>(
        creator_alt: &'b Option<String>,
        voter_alt: &'b Option<String>,
    ) -> Option<poll::PollVoteAddressing<'b>> {
        match (creator_alt, voter_alt) {
            (Some(c), Some(v)) => Some(poll::PollVoteAddressing {
                poll_creator_jid: c,
                voter_jid: v,
            }),
            _ => None,
        }
    }

    /// Decrypts each vote and tallies per-option results.
    /// Later votes from the same voter replace earlier ones (last-vote-wins).
    /// `votes` should be ordered oldest-first.
    ///
    /// Dedupes voters by their canonical (LID-preferred) identity so a voter who
    /// re-votes under the other namespace after migrating replaces, rather than
    /// duplicates, their earlier vote.
    pub async fn aggregate_votes(
        &self,
        poll_options: &[String],
        votes: &[(&Jid, PollVoteCiphertext<'_>)],
        message_secret: &[u8],
        poll_msg_id: &str,
        poll_creator_jid: &Jid,
    ) -> Result<Vec<PollOptionResult>, PollError> {
        let option_hashes: Vec<([u8; 32], &str)> = poll_options
            .iter()
            .map(|name| (poll::compute_option_hash(name), name.as_str()))
            .collect();

        // Creator addressing is constant across voters; resolve its counterpart once.
        let creator = poll_creator_jid.to_non_ad();
        let creator_str = creator.to_string();
        let creator_alt = self.swapped_user(&creator).await;

        // Keyed by canonical (LID-preferred) identity. The optional display JID
        // is only stored when it differs from the key. Last-vote-wins.
        let mut latest_votes: HashMap<String, (Option<String>, Vec<usize>)> =
            HashMap::with_capacity(votes.len());
        for (voter_jid, ciphertext) in votes {
            let voter = voter_jid.to_non_ad();
            let voter_str = voter.to_string();
            let voter_alt = self.swapped_user(&voter).await;
            let fallback = Self::build_fallback(&creator_alt, &voter_alt);
            let canonical_voter = if voter.is_lid() {
                voter_str.clone()
            } else {
                voter_alt.clone().unwrap_or_else(|| voter_str.clone())
            };
            match poll::decrypt_poll_vote_with_fallback(
                *ciphertext,
                message_secret,
                poll_msg_id,
                poll::PollVoteAddressing {
                    poll_creator_jid: &creator_str,
                    voter_jid: &voter_str,
                },
                fallback,
            ) {
                Ok(hashes) => {
                    let display_jid = if voter.is_lid() {
                        None
                    } else if voter_alt.is_some() {
                        Some(voter_str)
                    } else {
                        None
                    };
                    if hashes.is_empty() {
                        latest_votes.remove(canonical_voter.as_str());
                    } else {
                        let selected_indices: Vec<usize> = hashes
                            .iter()
                            .filter_map(|h| {
                                <[u8; 32]>::try_from(h.as_slice()).ok().and_then(|arr| {
                                    option_hashes.iter().position(|(oh, _)| *oh == arr)
                                })
                            })
                            .collect();
                        latest_votes.insert(canonical_voter, (display_jid, selected_indices));
                    }
                }
                Err(e) => {
                    log::warn!("Failed to decrypt vote from {voter_jid}: {e}");
                }
            }
        }

        let mut results: Vec<PollOptionResult> = poll_options
            .iter()
            .map(|name| PollOptionResult {
                name: name.clone(),
                voters: Vec::new(),
            })
            .collect();

        for (canonical_jid, (display_jid, selected_indices)) in latest_votes {
            let display_jid = display_jid.unwrap_or(canonical_jid);
            if let Some((last_idx, prefix_indices)) = selected_indices.split_last() {
                for idx in prefix_indices {
                    results[*idx].voters.push(display_jid.clone());
                }
                results[*last_idx].voters.push(display_jid);
            }
        }

        Ok(results)
    }
}

impl Client {
    pub fn polls(&self) -> Polls<'_> {
        Polls::new(self)
    }
}

/// Validate inputs and build a `PollCreationMessage`. A `Some(correct_index)`
/// produces a QUIZ; `None` produces a regular poll. Mirrors WA Web's
/// `GeneratePollCreationMessageProto` + `validatePollCreationMessage`, which require
/// `correctAnswer` iff `pollType == QUIZ`, with the chosen option carrying BOTH its
/// name and hash (even for text polls).
fn build_poll_creation_message(
    name: &str,
    options: &[String],
    selectable_count: u32,
    correct_index: Option<usize>,
) -> Result<wa::message::PollCreationMessage, PollError> {
    if options.len() < 2 {
        return Err(PollError::InvalidPoll(
            "poll must have at least 2 options".into(),
        ));
    }
    if options.len() > 12 {
        return Err(PollError::InvalidPoll(
            "polls can have a maximum of 12 options".into(),
        ));
    }
    if selectable_count < 1 || selectable_count > options.len() as u32 {
        return Err(PollError::InvalidPoll(format!(
            "selectable_count must be between 1 and {} (got {selectable_count})",
            options.len()
        )));
    }

    // Duplicate names would produce identical SHA-256 hashes, making votes indistinguishable
    let mut seen = std::collections::HashSet::new();
    for opt in options {
        if !seen.insert(opt) {
            return Err(PollError::InvalidPoll(format!(
                "duplicate option name: {opt}"
            )));
        }
    }

    let (poll_type, correct_answer) = match correct_index {
        Some(idx) => {
            let correct = options.get(idx).ok_or_else(|| {
                PollError::InvalidPoll(format!(
                    "correct_index {idx} out of range (poll has {} options)",
                    options.len()
                ))
            })?;
            let answer = wa::message::poll_creation_message::Option {
                option_name: Some(correct.clone()),
                // optionHash is the lowercase hex of SHA-256(name), matching WA Web's
                // createOptionHashHexFromString (the proto field is a string, not bytes).
                option_hash: Some(hex::encode(poll::compute_option_hash(correct))),
            };
            (
                Some(wa::message::PollType::QUIZ),
                buffa::MessageField::some(answer),
            )
        }
        None => (None, buffa::MessageField::none()),
    };

    let poll_options: Vec<wa::message::poll_creation_message::Option> = options
        .iter()
        .map(|name| wa::message::poll_creation_message::Option {
            option_name: Some(name.clone()),
            option_hash: None,
        })
        .collect();

    Ok(wa::message::PollCreationMessage {
        enc_key: None,
        name: Some(name.to_string()),
        options: poll_options,
        selectable_options_count: Some(selectable_count),
        context_info: buffa::MessageField::none(),
        // WA Web's GeneratePollCreationMessageProto always sets pollContentType
        // (TEXT=1 for a normal poll); omitting it drops a field the real client
        // always emits.
        poll_content_type: Some(wa::message::PollContentType::TEXT),
        poll_type,
        correct_answer,
        ..Default::default()
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lid_pn_cache::LearningSource;
    use crate::store::commands::DeviceCommand;
    use crate::test_utils::create_test_client;
    use std::sync::Arc;

    // poll/quiz message construction (build_poll_creation_message)

    #[test]
    fn regular_poll_has_no_quiz_fields() {
        let options = vec!["A".to_string(), "B".to_string(), "C".to_string()];
        let msg = build_poll_creation_message("Q?", &options, 2, None).unwrap();
        assert_eq!(msg.poll_type, None);
        assert!(msg.correct_answer.is_unset());
        assert_eq!(msg.selectable_options_count, Some(2));
        assert_eq!(
            msg.poll_content_type,
            Some(wa::message::PollContentType::TEXT)
        );
        assert_eq!(msg.options.len(), 3);
        assert!(msg.options.iter().all(|o| o.option_hash.is_none()));
    }

    #[test]
    fn quiz_sets_poll_type_and_correct_answer() {
        let options = vec!["A".to_string(), "B".to_string(), "C".to_string()];
        let msg = build_poll_creation_message("Q?", &options, 1, Some(1)).unwrap();
        assert_eq!(msg.poll_type, Some(wa::message::PollType::QUIZ));
        let answer = msg
            .correct_answer
            .as_option()
            .expect("quiz must carry a correct answer");
        // WA Web sets BOTH name and hash on the chosen option, even for text polls;
        // the hash is the lowercase hex of SHA-256(name).
        assert_eq!(answer.option_name.as_deref(), Some("B"));
        let expected_hash = hex::encode(poll::compute_option_hash("B"));
        assert_eq!(answer.option_hash.as_deref(), Some(expected_hash.as_str()));
    }

    #[test]
    fn quiz_rejects_out_of_range_correct_index() {
        let options = vec!["A".to_string(), "B".to_string()];
        assert!(build_poll_creation_message("Q?", &options, 1, Some(5)).is_err());
    }

    // encrypt-side voter selection (resolve_voter_jid)

    #[tokio::test]
    async fn voter_is_pn_when_poll_creator_is_pn() {
        let client: Arc<Client> = create_test_client().await;
        let own_pn = Jid::pn("5511999999999");
        let creator = Jid::pn("5511777777777");

        let voter = client
            .polls()
            .resolve_voter_jid(&creator, &own_pn, "POLLID")
            .await;
        assert_eq!(voter, own_pn);
    }

    #[tokio::test]
    async fn voter_is_own_lid_when_poll_creator_is_lid() {
        let client: Arc<Client> = create_test_client().await;
        let own_lid: Jid = "888000888000888:3@lid".parse().unwrap();
        client
            .persistence_manager
            .process_command(DeviceCommand::SetLid(Some(own_lid.clone())))
            .await;

        let own_pn = Jid::pn("5511999999999");
        let creator = Jid::lid("111000111000111");

        let voter = client
            .polls()
            .resolve_voter_jid(&creator, &own_pn, "POLLID")
            .await;
        assert!(voter.is_lid(), "voter must be LID-addressed in a LID poll");
        assert_eq!(voter.user, own_lid.user);
        assert_eq!(voter, own_lid.to_non_ad());
    }

    #[tokio::test]
    async fn voter_falls_back_to_pn_when_own_lid_unknown() {
        let client: Arc<Client> = create_test_client().await;
        // No SetLid, so lid() is None.
        let own_pn = Jid::pn("5511999999999");
        let creator = Jid::lid("111000111000111");

        let voter = client
            .polls()
            .resolve_voter_jid(&creator, &own_pn, "POLLID")
            .await;
        assert_eq!(voter, own_pn);
    }

    // decrypt-side LID/PN fallback

    /// A vote encrypted under the PN pair must still decrypt when the consumer
    /// only knows the LID JIDs, via the namespace-swap fallback.
    #[tokio::test]
    async fn decrypt_vote_recovers_when_fed_lid_but_encrypted_under_pn() {
        let client: Arc<Client> = create_test_client().await;
        let secret = [0x21u8; 32];
        let stanza_id = "3EB0POLLVOTE";

        let creator_pn = "5511777777777";
        let creator_lid = "111000111000111";
        let voter_pn = "5511888888888";
        let voter_lid = "222000222000222";

        client
            .add_lid_pn_mapping(creator_lid, creator_pn, LearningSource::Usync)
            .await
            .unwrap();
        client
            .add_lid_pn_mapping(voter_lid, voter_pn, LearningSource::Usync)
            .await
            .unwrap();

        let hashes = vec![poll::compute_option_hash("Yes").to_vec()];
        let (enc, iv) = poll::encrypt_poll_vote_with_secret(
            &hashes,
            &secret,
            stanza_id,
            &Jid::pn(creator_pn).to_string(),
            &Jid::pn(voter_pn).to_string(),
        )
        .unwrap();

        // Consumer feeds LID JIDs; primary (LID) fails, fallback swaps to PN.
        let out = client
            .polls()
            .decrypt_vote(
                PollVoteCiphertext {
                    enc_payload: &enc,
                    enc_iv: &iv,
                },
                &secret,
                stanza_id,
                &Jid::lid(creator_lid),
                &Jid::lid(voter_lid),
            )
            .await
            .expect("fallback should rescue the PN-encrypted vote");
        assert_eq!(out, hashes);
    }

    /// Without a known mapping there is no fallback pair, so a LID-fed decrypt
    /// of a PN-encrypted vote must fail rather than silently mis-decrypt.
    #[tokio::test]
    async fn decrypt_vote_fails_without_mapping() {
        let client: Arc<Client> = create_test_client().await;
        let secret = [0x21u8; 32];
        let stanza_id = "3EB0POLLVOTE";

        let (enc, iv) = poll::encrypt_poll_vote_with_secret(
            &[poll::compute_option_hash("Yes").to_vec()],
            &secret,
            stanza_id,
            &Jid::pn("5511777777777").to_string(),
            &Jid::pn("5511888888888").to_string(),
        )
        .unwrap();

        let res = client
            .polls()
            .decrypt_vote(
                PollVoteCiphertext {
                    enc_payload: &enc,
                    enc_iv: &iv,
                },
                &secret,
                stanza_id,
                &Jid::lid("111000111000111"),
                &Jid::lid("222000222000222"),
            )
            .await;
        assert!(res.is_err(), "no mapping → no fallback → must not decrypt");
    }

    #[tokio::test]
    async fn aggregate_votes_recovers_across_addressing() {
        let client: Arc<Client> = create_test_client().await;
        let secret = [0x31u8; 32];
        let stanza_id = "3EB0AGG";
        let options = vec!["Yes".to_string(), "No".to_string()];

        let creator_pn = "5511777777777";
        let creator_lid = "111000111000111";
        let voter_pn = "5511888888888";
        let voter_lid = "222000222000222";

        client
            .add_lid_pn_mapping(creator_lid, creator_pn, LearningSource::Usync)
            .await
            .unwrap();
        client
            .add_lid_pn_mapping(voter_lid, voter_pn, LearningSource::Usync)
            .await
            .unwrap();

        let (enc, iv) = poll::encrypt_poll_vote_with_secret(
            &[poll::compute_option_hash("Yes").to_vec()],
            &secret,
            stanza_id,
            &Jid::pn(creator_pn).to_string(),
            &Jid::pn(voter_pn).to_string(),
        )
        .unwrap();

        let voter_lid_jid = Jid::lid(voter_lid);
        let votes: Vec<(&Jid, PollVoteCiphertext)> = vec![(
            &voter_lid_jid,
            PollVoteCiphertext {
                enc_payload: &enc,
                enc_iv: &iv,
            },
        )];

        let results = client
            .polls()
            .aggregate_votes(&options, &votes, &secret, stanza_id, &Jid::lid(creator_lid))
            .await
            .unwrap();

        let yes = results.iter().find(|r| r.name == "Yes").unwrap();
        assert_eq!(yes.voters.len(), 1, "the LID voter's 'Yes' must be tallied");
        let no = results.iter().find(|r| r.name == "No").unwrap();
        assert!(no.voters.is_empty());
    }

    /// Same voter votes as PN then re-votes as LID after migrating. The
    /// canonical key must collapse them so last-vote-wins replaces, not
    /// duplicates, the earlier namespace's entry.
    #[tokio::test]
    async fn aggregate_dedupes_revote_across_namespace() {
        let client: Arc<Client> = create_test_client().await;
        let secret = [0x41u8; 32];
        let stanza_id = "3EB0REVOTE";
        let options = vec!["Yes".to_string(), "No".to_string()];

        let creator_pn = "5511777777777";
        let creator_lid = "111000111000111";
        let voter_pn = "5511888888888";
        let voter_lid = "222000222000222";
        client
            .add_lid_pn_mapping(creator_lid, creator_pn, LearningSource::Usync)
            .await
            .unwrap();
        client
            .add_lid_pn_mapping(voter_lid, voter_pn, LearningSource::Usync)
            .await
            .unwrap();

        // Oldest-first: PN "Yes", then LID "No".
        let (enc_pn, iv_pn) = poll::encrypt_poll_vote_with_secret(
            &[poll::compute_option_hash("Yes").to_vec()],
            &secret,
            stanza_id,
            &Jid::pn(creator_pn).to_string(),
            &Jid::pn(voter_pn).to_string(),
        )
        .unwrap();
        let (enc_lid, iv_lid) = poll::encrypt_poll_vote_with_secret(
            &[poll::compute_option_hash("No").to_vec()],
            &secret,
            stanza_id,
            &Jid::lid(creator_lid).to_string(),
            &Jid::lid(voter_lid).to_string(),
        )
        .unwrap();

        let voter_pn_jid = Jid::pn(voter_pn);
        let voter_lid_jid = Jid::lid(voter_lid);
        let votes: Vec<(&Jid, PollVoteCiphertext)> = vec![
            (
                &voter_pn_jid,
                PollVoteCiphertext {
                    enc_payload: &enc_pn,
                    enc_iv: &iv_pn,
                },
            ),
            (
                &voter_lid_jid,
                PollVoteCiphertext {
                    enc_payload: &enc_lid,
                    enc_iv: &iv_lid,
                },
            ),
        ];

        let results = client
            .polls()
            .aggregate_votes(&options, &votes, &secret, stanza_id, &Jid::lid(creator_lid))
            .await
            .unwrap();

        let yes = results.iter().find(|r| r.name == "Yes").unwrap();
        let no = results.iter().find(|r| r.name == "No").unwrap();
        assert!(yes.voters.is_empty(), "the PN 'Yes' must be replaced");
        assert_eq!(no.voters.len(), 1, "only the re-vote should count, once");
    }

    /// A clear-vote received under the other namespace must remove the prior
    /// vote, not leave a stale entry keyed by the original namespace.
    #[tokio::test]
    async fn aggregate_clears_vote_across_namespace() {
        let client: Arc<Client> = create_test_client().await;
        let secret = [0x51u8; 32];
        let stanza_id = "3EB0CLEAR";
        let options = vec!["Yes".to_string(), "No".to_string()];

        let creator_pn = "5511777777777";
        let creator_lid = "111000111000111";
        let voter_pn = "5511888888888";
        let voter_lid = "222000222000222";
        client
            .add_lid_pn_mapping(creator_lid, creator_pn, LearningSource::Usync)
            .await
            .unwrap();
        client
            .add_lid_pn_mapping(voter_lid, voter_pn, LearningSource::Usync)
            .await
            .unwrap();

        let (enc_pn, iv_pn) = poll::encrypt_poll_vote_with_secret(
            &[poll::compute_option_hash("Yes").to_vec()],
            &secret,
            stanza_id,
            &Jid::pn(creator_pn).to_string(),
            &Jid::pn(voter_pn).to_string(),
        )
        .unwrap();
        // Empty selection = clear, authored under the LID pair after migrating.
        let (enc_clear, iv_clear) = poll::encrypt_poll_vote_with_secret(
            &[],
            &secret,
            stanza_id,
            &Jid::lid(creator_lid).to_string(),
            &Jid::lid(voter_lid).to_string(),
        )
        .unwrap();

        let voter_pn_jid = Jid::pn(voter_pn);
        let voter_lid_jid = Jid::lid(voter_lid);
        let votes: Vec<(&Jid, PollVoteCiphertext)> = vec![
            (
                &voter_pn_jid,
                PollVoteCiphertext {
                    enc_payload: &enc_pn,
                    enc_iv: &iv_pn,
                },
            ),
            (
                &voter_lid_jid,
                PollVoteCiphertext {
                    enc_payload: &enc_clear,
                    enc_iv: &iv_clear,
                },
            ),
        ];

        let results = client
            .polls()
            .aggregate_votes(&options, &votes, &secret, stanza_id, &Jid::lid(creator_lid))
            .await
            .unwrap();

        assert!(
            results.iter().all(|r| r.voters.is_empty()),
            "the LID clear-vote must remove the earlier PN 'Yes'"
        );
    }
}