zcash_voting 0.10.2

Client-side library for Zcash shielded voting: ZKP delegation and vote-commitment proofs (Halo 2), ElGamal encryption, governance PCZT construction, Merkle witness generation, and SQLite round-state persistence.
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
use std::collections::HashSet;

use serde::{Deserialize, Serialize};

use crate::types::{ShareDelegationRecord, VotingError};

/// Seconds to wait after helper submission time before polling share status.
pub const SHARE_STATUS_CHECK_GRACE_SECONDS: u64 = 10;
/// Minimum seconds before an unconfirmed share is considered overdue.
pub const SHARE_MIN_OVERDUE_THRESHOLD_SECONDS: u64 = 30;
/// Maximum seconds before an unconfirmed share is considered overdue.
pub const SHARE_MAX_OVERDUE_THRESHOLD_SECONDS: u64 = 60 * 60;
/// Seconds near the vote end when resubmission should stop.
pub const SHARE_RESUBMIT_CUTOFF_SECONDS: u64 = 10;
/// Seconds between polls when all remaining shares are ready but unconfirmed.
pub const SHARE_READY_POLL_INTERVAL_SECONDS: u64 = 15;
/// Maximum seconds to wait for a future share to become ready.
pub const SHARE_FUTURE_CHECK_MAX_DELAY_SECONDS: u64 = 30;
/// Minimum seconds to sleep before the next tracking poll.
pub const SHARE_MIN_TRACKING_DELAY_SECONDS: u64 = 3;
/// Random bytes needed to sample an initial delayed share submission time.
pub const SHARE_SUBMIT_AT_RANDOM_BYTES: usize = 8;

/// Pure timing knobs for helper-share scheduling and recovery.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShareTimingPolicy {
    pub status_check_grace_seconds: u64,
    pub min_overdue_threshold_seconds: u64,
    pub max_overdue_threshold_seconds: u64,
    pub resubmit_cutoff_seconds: u64,
    pub ready_poll_interval_seconds: u64,
    pub future_check_max_delay_seconds: u64,
    pub min_tracking_delay_seconds: u64,
}

impl Default for ShareTimingPolicy {
    fn default() -> Self {
        Self {
            status_check_grace_seconds: SHARE_STATUS_CHECK_GRACE_SECONDS,
            min_overdue_threshold_seconds: SHARE_MIN_OVERDUE_THRESHOLD_SECONDS,
            max_overdue_threshold_seconds: SHARE_MAX_OVERDUE_THRESHOLD_SECONDS,
            resubmit_cutoff_seconds: SHARE_RESUBMIT_CUTOFF_SECONDS,
            ready_poll_interval_seconds: SHARE_READY_POLL_INTERVAL_SECONDS,
            future_check_max_delay_seconds: SHARE_FUTURE_CHECK_MAX_DELAY_SECONDS,
            min_tracking_delay_seconds: SHARE_MIN_TRACKING_DELAY_SECONDS,
        }
    }
}

/// Planned helper-share submission values that SDKs can apply to payloads.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShareSubmissionPlan {
    /// Unix seconds when helpers should submit the share, or 0 for immediate.
    pub submit_at: u64,
    /// Number of helpers each share should reach.
    pub target_count: u64,
    /// Helper targets selected for initial share submission.
    pub target_servers: Vec<String>,
}

/// Random byte counts needed to plan one or more share submissions.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShareSubmissionRandomBytesRequired {
    /// Bytes needed for independent delayed `submit_at` samples.
    pub submit_at_random_bytes: usize,
    /// Bytes needed for independent helper-order shuffles.
    pub server_random_bytes: usize,
}

/// Counts shares by their recovery status.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShareTrackingSummary {
    pub total: u64,
    pub confirmed: u64,
    pub waiting: u64,
    pub ready: u64,
    pub overdue: u64,
}

impl ShareTrackingSummary {
    pub fn has_shares(&self) -> bool {
        self.total > 0
    }
}

/// Return the time recovery should use as the share's base time.
///
/// Delayed shares use `submit_at`; immediate shares use `created_at`.
pub fn share_recovery_base_time(share: &ShareDelegationRecord) -> u64 {
    if share.submit_at > 0 {
        share.submit_at
    } else {
        share.created_at
    }
}

/// Return true once a helper has had enough time to process this share.
pub fn is_share_ready_for_status_check(
    share: &ShareDelegationRecord,
    now_seconds: u64,
    policy: ShareTimingPolicy,
) -> bool {
    if share.confirmed {
        return false;
    }
    now_seconds >= share_recovery_base_time(share).saturating_add(policy.status_check_grace_seconds)
}

/// Return the bounded overdue threshold for a share.
///
/// The threshold is one quarter of the remaining vote window from the share's
/// base time, bounded by the policy's minimum and maximum seconds.
pub fn overdue_threshold_seconds(
    share: &ShareDelegationRecord,
    vote_end_time_seconds: u64,
    policy: ShareTimingPolicy,
) -> u64 {
    let base_time = share_recovery_base_time(share);
    let remaining_window = vote_end_time_seconds.saturating_sub(base_time);
    let threshold = remaining_window / 4;
    let max_threshold = policy
        .max_overdue_threshold_seconds
        .max(policy.min_overdue_threshold_seconds);
    threshold
        .max(policy.min_overdue_threshold_seconds)
        .min(max_threshold)
}

/// Return true when a pending share should be retried immediately.
pub fn should_resubmit_share(
    share: &ShareDelegationRecord,
    now_seconds: u64,
    vote_end_time_seconds: u64,
    policy: ShareTimingPolicy,
) -> bool {
    if share.confirmed {
        return false;
    }
    let base_time = share_recovery_base_time(share);
    let retry_at = base_time.saturating_add(overdue_threshold_seconds(
        share,
        vote_end_time_seconds,
        policy,
    ));
    now_seconds >= retry_at
        && vote_end_time_seconds > now_seconds.saturating_add(policy.resubmit_cutoff_seconds)
}

/// Return the next delay after a share-status polling pass completes.
///
/// This mirrors the current wallet polling cadence. If any unconfirmed share is
/// still before its status-check grace time, the delay is the soonest future
/// check time capped by `future_check_max_delay_seconds`. If every unconfirmed
/// share is already ready, the delay is `ready_poll_interval_seconds` so callers
/// do not tight-loop on past check times. The returned delay is always at least
/// `min_tracking_delay_seconds`.
pub fn next_tracking_delay_seconds(
    shares: &[ShareDelegationRecord],
    now_seconds: u64,
    policy: ShareTimingPolicy,
) -> Option<u64> {
    let mut next_second: Option<u64> = None;
    let mut has_unconfirmed = false;

    for share in shares.iter().filter(|share| !share.confirmed) {
        has_unconfirmed = true;
        let base_time = share_recovery_base_time(share);
        let check_at = base_time.saturating_add(policy.status_check_grace_seconds);
        if check_at > now_seconds {
            next_second = min_second(next_second, check_at);
        }
    }

    if !has_unconfirmed {
        return None;
    }

    let delay_seconds = match next_second {
        Some(next) => next
            .saturating_sub(now_seconds)
            .min(policy.future_check_max_delay_seconds),
        None => policy.ready_poll_interval_seconds,
    };

    Some(delay_seconds.max(policy.min_tracking_delay_seconds))
}

/// Summarize share tracking state using the same precedence as wallet UIs.
pub fn summarize_share_tracking(
    shares: &[ShareDelegationRecord],
    now_seconds: u64,
    vote_end_time_seconds: Option<u64>,
    policy: ShareTimingPolicy,
) -> ShareTrackingSummary {
    let mut summary = ShareTrackingSummary {
        total: shares.len() as u64,
        confirmed: 0,
        waiting: 0,
        ready: 0,
        overdue: 0,
    };

    for share in shares {
        if share.confirmed {
            summary.confirmed += 1;
        } else if match vote_end_time_seconds {
            Some(vote_end_time_seconds) => {
                should_resubmit_share(share, now_seconds, vote_end_time_seconds, policy)
            }
            None => false,
        } {
            summary.overdue += 1;
        } else if is_share_ready_for_status_check(share, now_seconds, policy) {
            summary.ready += 1;
        } else {
            summary.waiting += 1;
        }
    }

    summary
}

/// Return the random bytes needed to sample a delayed share submission time.
///
/// `vote_end_time_seconds` is required because callers should only schedule
/// share submission for an active voting session. `last_moment_buffer_seconds`
/// is optional because some round timing data cannot produce a delayed-share
/// window. When the buffer is missing or zero, or when `single_share` is true,
/// no random bytes are needed because the share should be submitted
/// immediately.
pub fn share_submit_at_random_bytes_required(
    now_seconds: u64,
    vote_end_time_seconds: u64,
    last_moment_buffer_seconds: Option<u64>,
    single_share: bool,
) -> usize {
    if delayed_share_window_seconds(
        now_seconds,
        vote_end_time_seconds,
        last_moment_buffer_seconds,
        single_share,
    )
    .is_some()
    {
        SHARE_SUBMIT_AT_RANDOM_BYTES
    } else {
        0
    }
}

/// Plan the delayed helper submission time from a caller-provided random unit.
///
/// This is useful for deterministic tests and FFI callers that already expose a
/// random sample in the `[0, 1)` range. Production submission paths should use
/// `scheduled_share_submit_at_from_entropy` to keep sampling policy inside the
/// crate.
pub fn scheduled_share_submit_at_from_random_unit(
    now_seconds: u64,
    vote_end_time_seconds: u64,
    last_moment_buffer_seconds: Option<u64>,
    single_share: bool,
    random_unit: f64,
) -> Result<u64, VotingError> {
    let Some(window_seconds) = delayed_share_window_seconds(
        now_seconds,
        vote_end_time_seconds,
        last_moment_buffer_seconds,
        single_share,
    ) else {
        return Ok(0);
    };
    if !random_unit.is_finite() || !(0.0..1.0).contains(&random_unit) {
        return Err(VotingError::InvalidInput {
            message: "random_unit must be finite and in [0, 1)".to_string(),
        });
    }

    let delay_seconds = (random_unit * window_seconds as f64).floor() as u64;
    Ok(now_seconds.saturating_add(delay_seconds))
}

/// Plan the delayed helper submission time using caller-provided entropy.
///
/// `submit_at_random_bytes` must contain at least
/// `share_submit_at_random_bytes_required(...)` bytes from a cryptographically
/// secure RNG. No bytes are needed when the share should be submitted
/// immediately, and callers may pass 8 bytes unconditionally for simplicity.
pub fn scheduled_share_submit_at_from_entropy(
    now_seconds: u64,
    vote_end_time_seconds: u64,
    last_moment_buffer_seconds: Option<u64>,
    single_share: bool,
    submit_at_random_bytes: &[u8],
) -> Result<u64, VotingError> {
    let Some(window_seconds) = delayed_share_window_seconds(
        now_seconds,
        vote_end_time_seconds,
        last_moment_buffer_seconds,
        single_share,
    ) else {
        return Ok(0);
    };
    if submit_at_random_bytes.len() < SHARE_SUBMIT_AT_RANDOM_BYTES {
        return Err(VotingError::InvalidInput {
            message: format!(
                "submit_at_random_bytes must contain at least {SHARE_SUBMIT_AT_RANDOM_BYTES} bytes"
            ),
        });
    }

    let mut sample_bytes = [0u8; 8];
    sample_bytes.copy_from_slice(&submit_at_random_bytes[..8]);
    let sample = u64::from_le_bytes(sample_bytes);
    let delay_seconds = ((sample as u128 * window_seconds as u128) >> 64) as u64;
    Ok(now_seconds.saturating_add(delay_seconds))
}

fn delayed_share_window_seconds(
    now_seconds: u64,
    vote_end_time_seconds: u64,
    last_moment_buffer_seconds: Option<u64>,
    single_share: bool,
) -> Option<u64> {
    if single_share {
        return None;
    }

    let last_moment_buffer_seconds = last_moment_buffer_seconds?;
    if last_moment_buffer_seconds == 0 {
        return None;
    }

    let deadline = vote_end_time_seconds.saturating_sub(last_moment_buffer_seconds);
    if deadline <= now_seconds {
        return None;
    }

    Some(deadline - now_seconds)
}

/// Return how many helpers should receive each initial share.
///
/// This is half of the available helpers, rounded up, and 0 when there are no
/// helpers.
pub fn share_submission_target_count(server_count: usize) -> usize {
    if server_count == 0 {
        0
    } else {
        server_count / 2 + server_count % 2
    }
}

/// Return the number of random bytes needed to shuffle a server list.
///
/// The bytes should come from a cryptographically secure RNG. The crate owns the
/// shuffle policy, while SDKs only provide entropy from their platform RNG.
pub fn share_server_order_random_bytes_required(server_count: usize) -> usize {
    server_count
        .saturating_sub(1)
        .saturating_mul(std::mem::size_of::<u64>())
}

/// Return the random bytes needed to plan `share_count` independent shares.
///
/// Use these totals with `plan_share_submissions`. The returned counts are split
/// by purpose so callers can draw each byte slice from their platform CSPRNG and
/// pass the slices without having to understand the sampling layout.
pub fn share_submission_random_bytes_required(
    share_count: usize,
    server_count: usize,
    now_seconds: u64,
    vote_end_time_seconds: u64,
    last_moment_buffer_seconds: Option<u64>,
    single_share: bool,
) -> ShareSubmissionRandomBytesRequired {
    let submit_at_per_share = share_submit_at_random_bytes_required(
        now_seconds,
        vote_end_time_seconds,
        last_moment_buffer_seconds,
        single_share,
    );
    let server_per_share = share_server_order_random_bytes_required(server_count);

    ShareSubmissionRandomBytesRequired {
        submit_at_random_bytes: submit_at_per_share.saturating_mul(share_count),
        server_random_bytes: server_per_share.saturating_mul(share_count),
    }
}

/// Return the random bytes needed for `resubmission_server_order`.
pub fn resubmission_server_order_random_bytes_required(
    configured_server_urls: &[String],
    sent_to_urls: &[String],
) -> usize {
    let sent: HashSet<&str> = sent_to_urls.iter().map(String::as_str).collect();
    let untried_count = configured_server_urls
        .iter()
        .filter(|server| !sent.contains(server.as_str()))
        .count();
    let already_sent_count = configured_server_urls
        .iter()
        .filter(|server| sent.contains(server.as_str()))
        .count();
    share_server_order_random_bytes_required(untried_count)
        .saturating_add(share_server_order_random_bytes_required(already_sent_count))
}

/// Return a randomized helper-server order using caller-provided entropy.
///
/// `server_urls` must not contain duplicates. Duplicate helpers are treated as
/// configuration errors because target counts are based on distinct endpoints.
///
/// `random_bytes` must contain at least
/// `share_server_order_random_bytes_required(server_urls.len())` bytes from a
/// cryptographically secure RNG. Extra bytes are ignored.
pub fn shuffled_share_server_order(
    server_urls: &[String],
    random_bytes: &[u8],
) -> Result<Vec<String>, VotingError> {
    require_unique_share_servers(server_urls)?;
    let needed = share_server_order_random_bytes_required(server_urls.len());
    if random_bytes.len() < needed {
        return Err(VotingError::InvalidInput {
            message: format!(
                "server_random_bytes must contain at least {needed} bytes for {} servers",
                server_urls.len()
            ),
        });
    }

    let mut ordered = server_urls.to_vec();
    let mut offset = 0usize;
    for index in (1..ordered.len()).rev() {
        let mut sample_bytes = [0u8; 8];
        sample_bytes.copy_from_slice(&random_bytes[offset..offset + 8]);
        offset += 8;

        let sample = u64::from_le_bytes(sample_bytes);
        let swap_index = (sample % ((index + 1) as u64)) as usize;
        ordered.swap(index, swap_index);
    }
    Ok(ordered)
}

/// Select initial helper targets from a randomized server order.
///
/// Prefer this helper for production submission paths. It owns the privacy
/// sensitive randomization policy and only asks callers to provide CSPRNG bytes.
pub fn select_share_submission_targets(
    server_urls: &[String],
    target_count: usize,
    server_random_bytes: &[u8],
) -> Result<Vec<String>, VotingError> {
    let target_count = target_count.min(server_urls.len());
    if target_count == 0 {
        return Ok(Vec::new());
    }

    let randomized_order = shuffled_share_server_order(server_urls, server_random_bytes)?;
    Ok(select_share_submission_targets_from_order(
        &randomized_order,
        target_count,
    ))
}

/// Select initial helper targets from a caller-provided server order.
///
/// This is deterministic for tests and callers that have already made an
/// explicit ordering decision. Production submission paths should prefer
/// `select_share_submission_targets`.
pub fn select_share_submission_targets_from_order(
    server_urls: &[String],
    target_count: usize,
) -> Vec<String> {
    server_urls
        .iter()
        .take(target_count.min(server_urls.len()))
        .cloned()
        .collect()
}

/// Plan the timing and initial helper targets for a share delegation.
///
/// `server_urls` must not be empty. Missing helpers are a configuration error
/// for initial delegation, not a successful zero-target plan.
/// `server_urls` must also not contain duplicates because target counts are
/// based on distinct endpoints.
///
/// Missing or zero `last_moment_buffer_seconds` means there is no delayed-share
/// window, so the returned plan uses `submit_at = 0`. Helper targets are chosen
/// from a randomized server order using `server_random_bytes`. Callers can use
/// `share_submit_at_random_bytes_required` and
/// `share_server_order_random_bytes_required` to size the entropy inputs.
pub fn plan_share_submission(
    server_urls: &[String],
    now_seconds: u64,
    vote_end_time_seconds: u64,
    last_moment_buffer_seconds: Option<u64>,
    single_share: bool,
    submit_at_random_bytes: &[u8],
    server_random_bytes: &[u8],
) -> Result<ShareSubmissionPlan, VotingError> {
    require_share_servers(server_urls)?;
    let target_count = share_submission_target_count(server_urls.len());
    let target_servers =
        select_share_submission_targets(server_urls, target_count, server_random_bytes)?;
    let submit_at = scheduled_share_submit_at_from_entropy(
        now_seconds,
        vote_end_time_seconds,
        last_moment_buffer_seconds,
        single_share,
        submit_at_random_bytes,
    )?;

    Ok(ShareSubmissionPlan {
        submit_at,
        target_count: target_count as u64,
        target_servers,
    })
}

/// Plan independent timing and initial helper targets for multiple shares.
///
/// This is the preferred production helper when a wallet has multiple share
/// payloads. It consumes separate entropy for each returned plan so callers
/// cannot accidentally reuse one `submit_at` or helper target order for every
/// share. Use `share_submission_random_bytes_required` to size the two entropy
/// inputs.
pub fn plan_share_submissions(
    share_count: usize,
    server_urls: &[String],
    now_seconds: u64,
    vote_end_time_seconds: u64,
    last_moment_buffer_seconds: Option<u64>,
    single_share: bool,
    submit_at_random_bytes: &[u8],
    server_random_bytes: &[u8],
) -> Result<Vec<ShareSubmissionPlan>, VotingError> {
    if share_count == 0 {
        return Ok(Vec::new());
    }

    require_share_servers(server_urls)?;
    let submit_at_bytes_per_share = share_submit_at_random_bytes_required(
        now_seconds,
        vote_end_time_seconds,
        last_moment_buffer_seconds,
        single_share,
    );
    let server_bytes_per_share = share_server_order_random_bytes_required(server_urls.len());
    let submit_at_bytes_needed = checked_random_bytes_required(
        submit_at_bytes_per_share,
        share_count,
        "submit_at_random_bytes",
    )?;
    let server_bytes_needed =
        checked_random_bytes_required(server_bytes_per_share, share_count, "server_random_bytes")?;
    if submit_at_random_bytes.len() < submit_at_bytes_needed {
        return Err(VotingError::InvalidInput {
            message: format!(
                "submit_at_random_bytes must contain at least {submit_at_bytes_needed} bytes"
            ),
        });
    }
    if server_random_bytes.len() < server_bytes_needed {
        return Err(VotingError::InvalidInput {
            message: format!(
                "server_random_bytes must contain at least {server_bytes_needed} bytes"
            ),
        });
    }

    let mut plans = Vec::with_capacity(share_count);
    for share_index in 0..share_count {
        let submit_at_start = share_index * submit_at_bytes_per_share;
        let submit_at_end = submit_at_start + submit_at_bytes_per_share;
        let server_start = share_index * server_bytes_per_share;
        let server_end = server_start + server_bytes_per_share;
        plans.push(plan_share_submission(
            server_urls,
            now_seconds,
            vote_end_time_seconds,
            last_moment_buffer_seconds,
            single_share,
            &submit_at_random_bytes[submit_at_start..submit_at_end],
            &server_random_bytes[server_start..server_end],
        )?);
    }

    Ok(plans)
}

/// Plan share submission using a caller-provided helper order.
///
/// `server_urls` must not be empty. Missing helpers are a configuration error
/// for initial delegation, not a successful zero-target plan.
/// `server_urls` must also not contain duplicates because target counts are
/// based on distinct endpoints.
///
/// This is deterministic for tests and callers that have already made an
/// explicit ordering decision. Production submission paths should prefer
/// `plan_share_submission`.
pub fn plan_share_submission_from_order(
    server_urls: &[String],
    now_seconds: u64,
    vote_end_time_seconds: u64,
    last_moment_buffer_seconds: Option<u64>,
    single_share: bool,
    random_unit: f64,
) -> Result<ShareSubmissionPlan, VotingError> {
    require_share_servers(server_urls)?;
    let target_count = share_submission_target_count(server_urls.len());
    let target_servers = select_share_submission_targets_from_order(server_urls, target_count);
    plan_share_submission_with_targets(
        target_count,
        target_servers,
        now_seconds,
        vote_end_time_seconds,
        last_moment_buffer_seconds,
        single_share,
        random_unit,
    )
}

fn plan_share_submission_with_targets(
    target_count: usize,
    target_servers: Vec<String>,
    now_seconds: u64,
    vote_end_time_seconds: u64,
    last_moment_buffer_seconds: Option<u64>,
    single_share: bool,
    random_unit: f64,
) -> Result<ShareSubmissionPlan, VotingError> {
    let submit_at = scheduled_share_submit_at_from_random_unit(
        now_seconds,
        vote_end_time_seconds,
        last_moment_buffer_seconds,
        single_share,
        random_unit,
    )?;

    Ok(ShareSubmissionPlan {
        submit_at,
        target_count: target_count as u64,
        target_servers,
    })
}

fn require_share_servers(server_urls: &[String]) -> Result<(), VotingError> {
    if server_urls.is_empty() {
        return Err(VotingError::InvalidInput {
            message: "server_urls must not be empty".to_string(),
        });
    }

    require_unique_share_servers(server_urls)
}

fn require_unique_share_servers(server_urls: &[String]) -> Result<(), VotingError> {
    let mut seen = HashSet::new();
    for server_url in server_urls {
        if !seen.insert(server_url.as_str()) {
            return Err(VotingError::InvalidInput {
                message: "server_urls must not contain duplicates".to_string(),
            });
        }
    }

    Ok(())
}

fn checked_random_bytes_required(
    per_share: usize,
    share_count: usize,
    name: &str,
) -> Result<usize, VotingError> {
    per_share
        .checked_mul(share_count)
        .ok_or_else(|| VotingError::InvalidInput {
            message: format!("{name} requirement overflows usize"),
        })
}

/// Return resubmission order from separately ordered helper groups.
///
/// The returned order always tries untried helpers before helpers that already
/// received the share. This is deterministic for tests and callers that have
/// already made an explicit ordering decision. Production resubmission paths
/// should prefer `resubmission_server_order`.
pub fn resubmission_server_order_from_groups(
    untried_server_urls: &[String],
    already_sent_server_urls: &[String],
) -> Vec<String> {
    untried_server_urls
        .iter()
        .chain(already_sent_server_urls.iter())
        .cloned()
        .collect()
}

/// Return randomized resubmission order with untried helpers first.
///
/// The configured server list is split into untried and already-sent groups.
/// `configured_server_urls` must not contain duplicates because retry order is
/// based on distinct helper endpoints.
/// Each group is shuffled separately using `server_random_bytes`, then the
/// shuffled untried group is followed by the shuffled already-sent group.
/// Callers can use `resubmission_server_order_random_bytes_required` to size
/// the entropy input.
pub fn resubmission_server_order(
    configured_server_urls: &[String],
    sent_to_urls: &[String],
    server_random_bytes: &[u8],
) -> Result<Vec<String>, VotingError> {
    require_unique_share_servers(configured_server_urls)?;
    let sent: HashSet<&str> = sent_to_urls.iter().map(String::as_str).collect();
    let untried: Vec<String> = configured_server_urls
        .iter()
        .filter(|server| !sent.contains(server.as_str()))
        .cloned()
        .collect();
    let already_sent: Vec<String> = configured_server_urls
        .iter()
        .filter(|server| sent.contains(server.as_str()))
        .cloned()
        .collect();

    let untried_bytes = share_server_order_random_bytes_required(untried.len());
    let already_sent_bytes = share_server_order_random_bytes_required(already_sent.len());
    let needed =
        resubmission_server_order_random_bytes_required(configured_server_urls, sent_to_urls);
    if server_random_bytes.len() < needed {
        return Err(VotingError::InvalidInput {
            message: format!(
                "server_random_bytes must contain at least {needed} bytes for resubmission order"
            ),
        });
    }

    let randomized_untried =
        shuffled_share_server_order(&untried, &server_random_bytes[..untried_bytes])?;
    let randomized_already_sent = shuffled_share_server_order(
        &already_sent,
        &server_random_bytes[untried_bytes..untried_bytes + already_sent_bytes],
    )?;
    Ok(resubmission_server_order_from_groups(
        &randomized_untried,
        &randomized_already_sent,
    ))
}

/// Return resubmission order from configured helper order and already-sent set.
///
/// This preserves the configured order within each group. It is useful for
/// deterministic tests and callers that have already made an explicit ordering
/// decision. Production resubmission paths should prefer
/// `resubmission_server_order`.
pub fn resubmission_server_order_from_configured_order(
    configured_server_urls: &[String],
    sent_to_urls: &[String],
) -> Vec<String> {
    let sent: HashSet<&str> = sent_to_urls.iter().map(String::as_str).collect();
    let untried: Vec<String> = configured_server_urls
        .iter()
        .filter(|server| !sent.contains(server.as_str()))
        .cloned()
        .collect();
    let already_sent: Vec<String> = configured_server_urls
        .iter()
        .filter(|server| sent.contains(server.as_str()))
        .cloned()
        .collect();
    resubmission_server_order_from_groups(&untried, &already_sent)
}

fn min_second(current: Option<u64>, candidate: u64) -> Option<u64> {
    match current {
        Some(current) if current <= candidate => Some(current),
        _ => Some(candidate),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn share(submit_at: u64, created_at: u64) -> ShareDelegationRecord {
        ShareDelegationRecord {
            round_id: "round".to_string(),
            bundle_index: 0,
            proposal_id: 1,
            share_index: 0,
            sent_to_urls: vec!["https://helper.example.com".to_string()],
            nullifier: vec![7; 32],
            confirmed: false,
            submit_at,
            created_at,
        }
    }

    fn random_bytes(samples: &[u64]) -> Vec<u8> {
        samples
            .iter()
            .flat_map(|sample| sample.to_le_bytes())
            .collect()
    }

    #[test]
    fn scheduled_submit_at_from_random_unit_samples_before_deadline() {
        let submit_at =
            scheduled_share_submit_at_from_random_unit(1_000, 2_000, Some(100), false, 0.5)
                .unwrap();
        assert_eq!(submit_at, 1_450);
    }

    #[test]
    fn scheduled_submit_at_entropy_requirement_matches_delay_window() {
        assert_eq!(
            share_submit_at_random_bytes_required(1_000, 2_000, Some(100), false),
            SHARE_SUBMIT_AT_RANDOM_BYTES
        );
        assert_eq!(
            share_submit_at_random_bytes_required(1_000, 2_000, Some(100), true),
            0
        );
        assert_eq!(
            share_submit_at_random_bytes_required(1_000, 2_000, None, false),
            0
        );
        assert_eq!(
            share_submit_at_random_bytes_required(1_950, 2_000, Some(100), false),
            0
        );
    }

    #[test]
    fn scheduled_submit_at_from_entropy_samples_before_deadline() {
        let submit_at = scheduled_share_submit_at_from_entropy(
            1_000,
            2_000,
            Some(100),
            false,
            &random_bytes(&[1u64 << 63]),
        )
        .unwrap();
        assert_eq!(submit_at, 1_450);
    }

    #[test]
    fn scheduled_submit_at_is_immediate_without_a_delay_window() {
        assert_eq!(
            scheduled_share_submit_at_from_random_unit(1_000, 2_000, Some(100), true, f64::NAN)
                .unwrap(),
            0
        );
        assert_eq!(
            scheduled_share_submit_at_from_random_unit(1_000, 2_000, None, false, f64::NAN)
                .unwrap(),
            0
        );
        assert_eq!(
            scheduled_share_submit_at_from_random_unit(1_000, 2_000, Some(0), false, f64::NAN)
                .unwrap(),
            0
        );
        assert_eq!(
            scheduled_share_submit_at_from_random_unit(1_950, 2_000, Some(100), false, f64::NAN)
                .unwrap(),
            0
        );
        assert_eq!(
            scheduled_share_submit_at_from_entropy(1_000, 2_000, Some(100), true, &[]).unwrap(),
            0
        );
    }

    #[test]
    fn scheduled_submit_at_rejects_non_finite_random_unit_for_delay_window() {
        assert!(matches!(
            scheduled_share_submit_at_from_random_unit(1_000, 2_000, Some(100), false, f64::NAN),
            Err(VotingError::InvalidInput { .. })
        ));
    }

    #[test]
    fn scheduled_submit_at_from_entropy_rejects_missing_entropy_for_delay_window() {
        assert!(matches!(
            scheduled_share_submit_at_from_entropy(1_000, 2_000, Some(100), false, &[]),
            Err(VotingError::InvalidInput { .. })
        ));
    }

    #[test]
    fn scheduled_submit_at_from_random_unit_rejects_out_of_range_samples() {
        assert!(matches!(
            scheduled_share_submit_at_from_random_unit(1_000, 2_000, Some(100), false, 1.0),
            Err(VotingError::InvalidInput { .. })
        ));
        assert!(matches!(
            scheduled_share_submit_at_from_random_unit(1_000, 2_000, Some(100), false, -1.0),
            Err(VotingError::InvalidInput { .. })
        ));
    }

    #[test]
    fn immediate_shares_use_created_at_for_status_and_retry() {
        let share = share(0, 100);
        let policy = ShareTimingPolicy::default();

        assert_eq!(share_recovery_base_time(&share), 100);
        assert!(!is_share_ready_for_status_check(&share, 109, policy));
        assert!(is_share_ready_for_status_check(&share, 110, policy));
        assert!(!should_resubmit_share(&share, 129, 200, policy));
        assert!(should_resubmit_share(&share, 130, 200, policy));
    }

    #[test]
    fn delayed_shares_use_submit_at_for_status_and_retry() {
        let share = share(200, 100);
        let policy = ShareTimingPolicy::default();

        assert_eq!(share_recovery_base_time(&share), 200);
        assert!(!is_share_ready_for_status_check(&share, 209, policy));
        assert!(is_share_ready_for_status_check(&share, 210, policy));
        assert!(!should_resubmit_share(&share, 229, 320, policy));
        assert!(should_resubmit_share(&share, 230, 320, policy));
    }

    #[test]
    fn overdue_threshold_is_quarter_window_with_bounds() {
        let share = share(0, 100);
        let policy = ShareTimingPolicy::default();

        assert_eq!(overdue_threshold_seconds(&share, 500, policy), 100);
        assert_eq!(overdue_threshold_seconds(&share, 120, policy), 30);
        assert_eq!(overdue_threshold_seconds(&share, 20_000, policy), 3_600);
    }

    #[test]
    fn should_resubmit_respects_vote_end_cutoff() {
        let share = share(0, 100);
        let policy = ShareTimingPolicy::default();

        assert!(should_resubmit_share(&share, 130, 200, policy));
        assert!(!should_resubmit_share(&share, 190, 200, policy));
    }

    #[test]
    fn next_tracking_delay_uses_future_check_times() {
        let shares = vec![share(0, 100), share(200, 100)];
        let policy = ShareTimingPolicy::default();

        assert_eq!(next_tracking_delay_seconds(&shares, 105, policy), Some(5));
    }

    #[test]
    fn next_tracking_delay_applies_minimum_and_future_cap() {
        let shares = vec![share(0, 100), share(200, 100)];
        let policy = ShareTimingPolicy::default();

        assert_eq!(next_tracking_delay_seconds(&shares, 109, policy), Some(3));
        assert_eq!(next_tracking_delay_seconds(&shares, 111, policy), Some(30));
    }

    #[test]
    fn next_tracking_delay_uses_ready_poll_interval_for_ready_pending_shares() {
        let shares = vec![share(0, 100)];
        let policy = ShareTimingPolicy::default();

        assert_eq!(next_tracking_delay_seconds(&shares, 130, policy), Some(15));
        assert_eq!(next_tracking_delay_seconds(&shares, 131, policy), Some(15));
    }

    #[test]
    fn next_tracking_delay_stops_when_all_shares_are_confirmed() {
        let mut confirmed = share(0, 100);
        confirmed.confirmed = true;

        assert_eq!(
            next_tracking_delay_seconds(&[confirmed], 130, ShareTimingPolicy::default()),
            None
        );
    }

    #[test]
    fn tracking_summary_uses_confirmed_overdue_ready_waiting_order() {
        let mut confirmed = share(0, 100);
        confirmed.confirmed = true;
        let overdue = share(0, 100);
        let ready = share(120, 100);
        let waiting = share(300, 100);
        let shares = vec![confirmed, overdue, ready, waiting];

        let summary =
            summarize_share_tracking(&shares, 130, Some(200), ShareTimingPolicy::default());

        assert_eq!(
            summary,
            ShareTrackingSummary {
                total: 4,
                confirmed: 1,
                waiting: 1,
                ready: 1,
                overdue: 1,
            }
        );
        assert!(summary.has_shares());
    }

    #[test]
    fn helper_target_count_is_half_rounded_up() {
        assert_eq!(share_submission_target_count(0), 0);
        assert_eq!(share_submission_target_count(1), 1);
        assert_eq!(share_submission_target_count(2), 1);
        assert_eq!(share_submission_target_count(3), 2);
        assert_eq!(share_submission_target_count(5), 3);
    }

    #[test]
    fn helper_order_random_bytes_required_matches_shuffle_steps() {
        assert_eq!(share_server_order_random_bytes_required(0), 0);
        assert_eq!(share_server_order_random_bytes_required(1), 0);
        assert_eq!(share_server_order_random_bytes_required(3), 16);
    }

    #[test]
    fn resubmission_order_random_bytes_required_matches_group_shuffles() {
        let configured = vec![
            "https://already-one.example.com".to_string(),
            "https://untried-one.example.com".to_string(),
            "https://untried-two.example.com".to_string(),
            "https://already-two.example.com".to_string(),
        ];
        let sent = vec![
            "https://already-one.example.com".to_string(),
            "https://already-two.example.com".to_string(),
        ];

        assert_eq!(
            resubmission_server_order_random_bytes_required(&configured, &sent),
            16
        );
    }

    #[test]
    fn randomized_helper_order_uses_entropy() {
        let servers = vec![
            "https://one.example.com".to_string(),
            "https://two.example.com".to_string(),
            "https://three.example.com".to_string(),
        ];

        let ordered = shuffled_share_server_order(&servers, &random_bytes(&[1, 0])).unwrap();

        assert_eq!(
            ordered,
            vec![
                "https://three.example.com".to_string(),
                "https://one.example.com".to_string(),
                "https://two.example.com".to_string()
            ]
        );
    }

    #[test]
    fn randomized_helper_order_rejects_missing_entropy() {
        let servers = vec![
            "https://one.example.com".to_string(),
            "https://two.example.com".to_string(),
        ];

        assert!(matches!(
            shuffled_share_server_order(&servers, &[]),
            Err(VotingError::InvalidInput { .. })
        ));
    }

    #[test]
    fn randomized_helper_order_rejects_duplicate_server_urls() {
        let servers = vec![
            "https://one.example.com".to_string(),
            "https://one.example.com".to_string(),
        ];

        assert!(matches!(
            shuffled_share_server_order(&servers, &random_bytes(&[0])),
            Err(VotingError::InvalidInput { .. })
        ));
    }

    #[test]
    fn share_submission_plan_randomizes_target_servers() {
        let servers = vec![
            "https://one.example.com".to_string(),
            "https://two.example.com".to_string(),
            "https://three.example.com".to_string(),
        ];

        let plan = plan_share_submission(
            &servers,
            1_000,
            2_000,
            Some(100),
            false,
            &random_bytes(&[1u64 << 63]),
            &random_bytes(&[1, 0]),
        )
        .unwrap();

        assert_eq!(plan.submit_at, 1_450);
        assert_eq!(plan.target_count, 2);
        assert_eq!(
            plan.target_servers,
            vec![
                "https://three.example.com".to_string(),
                "https://one.example.com".to_string()
            ]
        );
    }

    #[test]
    fn share_submission_plan_rejects_empty_server_list() {
        assert!(matches!(
            plan_share_submission(
                &[],
                1_000,
                2_000,
                Some(100),
                false,
                &random_bytes(&[1u64 << 63]),
                &[]
            ),
            Err(VotingError::InvalidInput { .. })
        ));
        assert!(matches!(
            plan_share_submission_from_order(&[], 1_000, 2_000, Some(100), false, 0.0),
            Err(VotingError::InvalidInput { .. })
        ));
    }

    #[test]
    fn share_submission_plan_rejects_duplicate_server_urls() {
        let servers = vec![
            "https://one.example.com".to_string(),
            "https://one.example.com".to_string(),
        ];

        assert!(matches!(
            plan_share_submission(
                &servers,
                1_000,
                2_000,
                Some(100),
                false,
                &random_bytes(&[1u64 << 63]),
                &random_bytes(&[0])
            ),
            Err(VotingError::InvalidInput { .. })
        ));
        assert!(matches!(
            plan_share_submission_from_order(&servers, 1_000, 2_000, Some(100), false, 0.0),
            Err(VotingError::InvalidInput { .. })
        ));
    }

    #[test]
    fn share_submission_random_bytes_required_counts_independent_share_plans() {
        assert_eq!(
            share_submission_random_bytes_required(2, 3, 1_000, 2_000, Some(100), false),
            ShareSubmissionRandomBytesRequired {
                submit_at_random_bytes: 16,
                server_random_bytes: 32,
            }
        );
        assert_eq!(
            share_submission_random_bytes_required(2, 3, 1_000, 2_000, Some(100), true),
            ShareSubmissionRandomBytesRequired {
                submit_at_random_bytes: 0,
                server_random_bytes: 32,
            }
        );
    }

    #[test]
    fn share_submission_batch_plan_uses_independent_entropy_per_share() {
        let servers = vec![
            "https://one.example.com".to_string(),
            "https://two.example.com".to_string(),
            "https://three.example.com".to_string(),
        ];

        let plans = plan_share_submissions(
            2,
            &servers,
            1_000,
            2_000,
            Some(100),
            false,
            &random_bytes(&[0, 1u64 << 63]),
            &random_bytes(&[1, 0, 0, 1]),
        )
        .unwrap();

        assert_eq!(plans.len(), 2);
        assert_eq!(plans[0].submit_at, 1_000);
        assert_eq!(
            plans[0].target_servers,
            vec![
                "https://three.example.com".to_string(),
                "https://one.example.com".to_string()
            ]
        );
        assert_eq!(plans[1].submit_at, 1_450);
        assert_eq!(
            plans[1].target_servers,
            vec![
                "https://three.example.com".to_string(),
                "https://two.example.com".to_string()
            ]
        );
    }

    #[test]
    fn share_submission_batch_plan_rejects_missing_entropy() {
        let servers = vec![
            "https://one.example.com".to_string(),
            "https://two.example.com".to_string(),
            "https://three.example.com".to_string(),
        ];

        assert!(matches!(
            plan_share_submissions(
                2,
                &servers,
                1_000,
                2_000,
                Some(100),
                false,
                &random_bytes(&[0]),
                &random_bytes(&[1, 0, 0, 1]),
            ),
            Err(VotingError::InvalidInput { .. })
        ));
        assert!(matches!(
            plan_share_submissions(
                2,
                &servers,
                1_000,
                2_000,
                Some(100),
                false,
                &random_bytes(&[0, 1u64 << 63]),
                &random_bytes(&[1, 0, 0]),
            ),
            Err(VotingError::InvalidInput { .. })
        ));
    }

    #[test]
    fn share_submission_plan_from_order_uses_caller_server_order() {
        let servers = vec![
            "https://one.example.com".to_string(),
            "https://two.example.com".to_string(),
            "https://three.example.com".to_string(),
        ];

        let plan = plan_share_submission_from_order(&servers, 1_000, 2_000, Some(100), false, 0.0)
            .unwrap();

        assert_eq!(plan.submit_at, 1_000);
        assert_eq!(plan.target_count, 2);
        assert_eq!(
            plan.target_servers,
            vec![
                "https://one.example.com".to_string(),
                "https://two.example.com".to_string()
            ]
        );
    }

    #[test]
    fn share_submission_target_selection_uses_caller_server_order() {
        let servers = vec![
            "https://three.example.com".to_string(),
            "https://one.example.com".to_string(),
            "https://two.example.com".to_string(),
        ];

        assert_eq!(
            select_share_submission_targets_from_order(&servers, 2),
            vec![
                "https://three.example.com".to_string(),
                "https://one.example.com".to_string()
            ]
        );
    }

    #[test]
    fn randomized_share_submission_target_selection_uses_entropy() {
        let servers = vec![
            "https://one.example.com".to_string(),
            "https://two.example.com".to_string(),
            "https://three.example.com".to_string(),
        ];

        assert_eq!(
            select_share_submission_targets(&servers, 2, &random_bytes(&[1, 0])).unwrap(),
            vec![
                "https://three.example.com".to_string(),
                "https://one.example.com".to_string()
            ]
        );
    }

    #[test]
    fn resubmission_order_tries_ordered_untried_helpers_first() {
        let untried = vec![
            "https://untried-two.example.com".to_string(),
            "https://untried-one.example.com".to_string(),
        ];
        let already_sent = vec!["https://already.example.com".to_string()];

        assert_eq!(
            resubmission_server_order_from_groups(&untried, &already_sent),
            vec![
                "https://untried-two.example.com".to_string(),
                "https://untried-one.example.com".to_string(),
                "https://already.example.com".to_string()
            ]
        );
    }

    #[test]
    fn randomized_resubmission_order_shuffles_groups_separately() {
        let configured = vec![
            "https://already-one.example.com".to_string(),
            "https://untried-one.example.com".to_string(),
            "https://untried-two.example.com".to_string(),
            "https://already-two.example.com".to_string(),
        ];
        let sent = vec![
            "https://already-one.example.com".to_string(),
            "https://already-two.example.com".to_string(),
        ];

        assert_eq!(
            resubmission_server_order(&configured, &sent, &random_bytes(&[0, 0])).unwrap(),
            vec![
                "https://untried-two.example.com".to_string(),
                "https://untried-one.example.com".to_string(),
                "https://already-two.example.com".to_string(),
                "https://already-one.example.com".to_string()
            ]
        );
    }

    #[test]
    fn randomized_resubmission_order_rejects_missing_entropy() {
        let configured = vec![
            "https://untried-one.example.com".to_string(),
            "https://untried-two.example.com".to_string(),
        ];

        assert!(matches!(
            resubmission_server_order(&configured, &[], &[]),
            Err(VotingError::InvalidInput { .. })
        ));
    }

    #[test]
    fn randomized_resubmission_order_rejects_duplicate_configured_urls() {
        let configured = vec![
            "https://untried-one.example.com".to_string(),
            "https://untried-one.example.com".to_string(),
        ];

        assert!(matches!(
            resubmission_server_order(&configured, &[], &random_bytes(&[0])),
            Err(VotingError::InvalidInput { .. })
        ));
    }

    #[test]
    fn resubmission_order_from_configured_order_preserves_group_order() {
        let configured = vec![
            "https://already.example.com".to_string(),
            "https://untried.example.com".to_string(),
        ];
        let sent = vec!["https://already.example.com".to_string()];

        assert_eq!(
            resubmission_server_order_from_configured_order(&configured, &sent),
            vec![
                "https://untried.example.com".to_string(),
                "https://already.example.com".to_string()
            ]
        );
    }
}