tor-dirserver 0.48.0

Implements dirserver functionality
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
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
//! Directory Mirror Operation.
//!
//! # Specifications
//!
//! * [Directory cache operation](https://spec.torproject.org/dir-spec/directory-cache-operation.html).
//!
//! # Rationale
//!
//! This module implements the "core operation" of a directory mirror.
//! "Core operation" primarily refers to the logic involved in downloading
//! network documents from an upstream authority and inserting them into the
//! database.  This module notably **DOES NOT** provide any public (in the HTTP
//! sense) endpoints for querying documents.  This is purposely behind a different
//! module, so that the directory authority implementation can also make use of it.
//! You can think of this module as the one implementing the things unique
//! to directory mirrors.

use std::{
    collections::{HashMap, HashSet, VecDeque},
    fmt::Debug,
    hash::Hash,
    marker::PhantomData,
    mem,
    net::SocketAddr,
    time::Duration,
};

use educe::Educe;
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use rand::Rng;
use rusqlite::Transaction;
use tokio::net::TcpStream;
use tokio_util::compat::TokioAsyncReadCompatExt;
use tor_checkable::TimeBound;
use tor_dirclient::{
    Error as DirClientError, RequestError, RequestFailedError,
    request::{
        AuthCertRequest, ConsensusRequest, MicrodescRequest, Requestable, RouterDescRequest,
    },
};
use tor_dircommon::{authority::AuthorityContacts, config::DirTolerance};
use tor_error::internal;
use tor_netdoc::{
    doc::{
        authcert::{AuthCert, AuthCertKeyIds, AuthCertUnverified},
        microdesc::Microdesc,
        netstatus::{ConsensusFlavor, ConsensusVerifiabilityError},
        routerdesc::RouterDescUnverified,
    },
    parse2::{
        self, NetdocParseable, NetdocParseableUnverified, ParseError, ParseInput, VerifyFailed,
    },
};
use tor_rtcompat::PreferredRuntime;
use tracing::{debug, warn};

use crate::{
    database::{
        self as db, AuthCertMeta, ConsensusMeta, ContentEncoding, DescriptorMeta, Sha1, Sha256,
        Timestamp,
    },
    err::{AuthorityRequestError, DatabaseError, OperationError},
    types::{
        FlavoredConsensusUnverified, FlavoredDescriptor, FlavoredDescriptorMd,
        FlavoredDescriptorPlain,
    },
};

mod poc;

/// The duration to try verifying an unverified consensus.
///
/// This exists primarily to properly handle the
/// [`ConsensusVerifiabilityError::InsufficientTrustedSigners`] error.  Besides,
/// it also serves as an upper-limit for the time we can spend in the phase for
/// fetching authority certificates, which could otherwise run for a very long
/// time, as long as every request makes progress and finishes before a
/// connection timeout is reached.
///
/// Obviously, we cannot use the values inside the consensus, as they are
/// untrusted.
const UNVERIFIED_TTL: Duration = Duration::from_mins(10);

/// Query a maximum.
const DESCRIPTOR_LIMIT: Option<u64> = Some(92);

/// The endpoint(s) of a download authority identifying it.
type DownloadAuthority = [SocketAddr];

/// The various states for the [`StaticEngine`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display)]
enum State {
    /// Loads the most recent valid (and verified) consensus from the database
    /// into memory.
    ///
    /// Transitions from:
    /// * Start, if a recent valid consensus exists in the database.
    /// * [`State::StoreConsensus`], if successfully finished.
    ///
    /// Transitions into:
    /// * [`State::Descriptors`]
    LoadConsensus,

    /// Downloads the most recent consensus from a directory authority.
    ///
    /// Transitions from:
    /// * Start, if no recent valid consensus exists in the database.
    /// * [`State::Descriptors`], if ttl is over.
    /// * [`State::Hibernate`], if ttl is over.
    ///
    /// Transitions into:
    /// * [`State::AuthCerts`], if we miss authority certificates.
    /// * [`State::StoreConsensus`], if all authority certificates exist in the
    ///   database.
    /// * [`State::Hibernate`], if we have insufficient trusted authorities.
    // TODO DIRMIRROR: What to do in the case of getting an invalid consensus
    // such as junk data?  The normal retry logic sounds reasonable here.
    FetchConsensus,

    /// Downloads, validates, and stores the missing authority certificates from
    /// the downloaded unvalidated consensus into the database.
    ///
    /// Transitions from:
    /// * [`State::FetchConsensus`], if we miss authority certificates.
    /// * [`State::AuthCerts`], if we still miss authority certificates.
    ///
    /// Transitions into:
    /// * [`State::AuthCerts`], if we still miss authority certificates.
    /// * [`State::StoreConsensus`], if we got all authority certificates.
    AuthCerts,

    /// Validates and stores the downloaded unvalidated consensus into the
    /// database.
    ///
    /// Transitions from:
    /// * [`State::FetchConsensus`], if we have all authority certificates.
    /// * [`State::AuthCerts`], if we have all authority certificates.
    ///
    /// Transitions into:
    /// * [`State::LoadConsensus`]
    StoreConsensus,

    /// Downloads missing network documents (descriptors) from a directory
    /// authority.
    ///
    /// Transitions from:
    /// * [`State::LoadConsensus`], if we initialize.
    /// * [`State::Descriptors`], if we still have missing descriptors left.
    ///
    /// Transitions into:
    /// * [`State::FetchConsensus`], if ttl is over.
    /// * [`State::Descriptors`], if we still have missing descriptors left.
    /// * [`State::Hibernate`], if nothing is left.
    Descriptors,

    /// Hibernate because nothing is left.
    ///
    /// Transitions from:
    /// * [`State::FetchConsensus`], if we have insufficient trusted
    ///   authorities.
    /// * [`State::Descriptors`], if we have downloaded all descriptors.
    ///
    /// Transitions into:
    /// * [`State::FetchConsensus`], if the ttl is over.
    Hibernate,
}

/// The execution engine for the finite state machine.
///
/// The states themselves are explained in [`State`].
///
/// This data structure itself is static and contains no state, but merely
/// configuration primitives that stay constant throughout the runtime of the
/// program, such as the [`AuthorityContacts`], and the
/// [`DirTolerance`].  It can be kept throughout the entire runtime and only
/// consists for convenience in order to not give each state machine related
/// (then static) method a super long signature containing these fields.
///
/// Besides these dynamic fields, there is also a generic parameter specifying
/// the consensus flavor that is being used.
///
/// The state itself is computed fully deterministically from the data found
/// within the database and [`ConsensusBoundData`].
///
/// This is the reason on why this structure is not called `StateMachine`,
/// because this implies that the type in itself carries state, which is not
/// true, because the state is stored entirely external, with this engine
/// only processing and modifying it.
///
/// See [`StaticEngine::determine_state()`] for more details.
#[derive(Debug)]
struct StaticEngine<T> {
    /// The authorities we are acknowledging.
    authorities: AuthorityContacts,

    /// The document tolerance we are accepting.
    tolerance: DirTolerance,

    /// The preferred runtime for compatibility with other arti crates.
    ///
    /// Generally obtained through [`PreferredRuntime::current()`].
    rt: PreferredRuntime,

    /// The content encodings we apply to documents.
    encodings: HashSet<ContentEncoding>,

    /// Utilizes the generic type parameter.
    _phantom: PhantomData<T>,
}

/// Additional state machine data concerning a single consensus.
///
/// This data type exists to store data that cannot be stored in the database,
/// including the consensus that is currently verified, the consensus that is
/// currently served, the timestamp until we will serve it, etc.
///
/// # Field Requirements
///
/// In order for a field to be contained here, at least one of the following
/// criteria should be met:
/// * The item needs to persist between multiple invocation and cannot be
///   obtained from the database.
/// * The item itself serves as an identifier to the database and querying it
///   it again can not be done in a pure fashion, e.g. a [`ConsensusMeta`]
///   identifier.
/// * The item exists purely for optimization purposes and can be thrown away
///   at any time without data loss, such as content-addressable caches.
///   These caches must be pure in the sense that a cache miss must always
///   return the same result as a cache hit and vice versa.
//
// TODO DIRMIRROR: This is probably better of as a struct instead of an enum.
#[derive(Debug, Clone)]
enum ConsensusBoundData<T: FlavoredConsensusUnverified> {
    /// No state is loaded in memory at the moment.
    None,

    /// We have downloaded a consensus but it is not yet verified.
    Unverified {
        /// The unverified parsed consensus we have.
        consensus: T,

        /// The unparsed raw consensus we have.
        raw: String,

        /// When to stop dealing with this consensus and download again.
        ///
        /// Useful to have in order to not stuck forever in a verification
        /// loop, i.e. due to unavailable authentication certificates, etc.
        ttl: Timestamp,
    },

    /// We have downloaded and verified a consensus.
    Verified {
        /// The verified consensus we have.
        ///
        /// Contained in this structure because it is the only way we can
        /// uniquely identify a consensus, which is crucial for operation, as
        /// things like the `ttl` are derived from it.
        ///
        /// While methods like [`ConsensusMeta::query`] would probably also
        /// work correctly, relying on them feels rather wrong, as they were
        /// not made to be pure.
        consensus: ConsensusMeta<T>,

        /// When to stop dealing with this consensus and fetching a new one.
        ttl: Timestamp,

        /// Descriptors we refuse to further download.
        ///
        /// Right now, this state gets cleaned, everytime we restart or obtain
        /// a new consensus.  This is probably okay, as we most likely do not
        /// want to store it on disk.
        futile: Box<FutileDescriptors>,
    },
}

impl<T: FlavoredConsensusUnverified> StaticEngine<T> {
    /// Determines the [`State`] only from the database and [`ConsensusBoundData`].
    ///
    /// This method is fully idempotent, meaning it only depends upon the data
    /// found within the database and the [`ConsensusBoundData`]; there is no
    /// internal `state` variable or something contained within [`StaticEngine`].
    fn determine_state(
        &self,
        tx: &Transaction<'_>,
        data: &ConsensusBoundData<T>,
        now: Timestamp,
    ) -> Result<State, DatabaseError> {
        // Determine the state primarily upon ConsensusBoundData combined with
        // a few database queries, as well as the current time of course.
        let state = match data {
            // ConsensusBoundData::None means that we currently have no
            // consensus in memory.  This may be the case because we just
            // started up or because we just downloaded, validated, and inserted
            // a consensus into the database and reset ConsensusBoundData to
            // None afterwards.
            ConsensusBoundData::None => {
                // Check whether there is a valid consensus in the database at all.
                match self.recent_consensus(tx, now)? {
                    // Some consensus means we can load it.
                    Some(_) => State::LoadConsensus,

                    // None means we must download it.
                    None => State::FetchConsensus,
                }
            }

            // ConsensusBoundData::Unverified means that we recently downloaded
            // a consensus through State::FetchConsensus.  It is not fully
            // validated yet and we may not even be able due to missing
            // authority certificates.
            ConsensusBoundData::Unverified { consensus, ttl, .. } if now < *ttl => {
                let certs_already = self.certs_already(tx, now)?;
                match consensus.can_verify(self.authorities.v3idents(), &certs_already) {
                    // We can verify and insert the consensus.
                    Ok(()) => State::StoreConsensus,

                    // We will never be able to verify the consensus, better
                    // times may come ...
                    Err(ConsensusVerifiabilityError::InsufficientTrustedSigners) => {
                        State::Hibernate
                    }

                    // We need to fetch more authority certificates from the
                    // network.
                    Err(ConsensusVerifiabilityError::MissingAuthCerts { .. }) => State::AuthCerts,
                }
            }

            ConsensusBoundData::Unverified { .. } => State::FetchConsensus,

            // ConsensusBoundData::Verified means that we have successfully
            // loaded a recent valid consensus from the database using
            // State::LoadConsensus.  Depending on this, we download the missing
            // network documents (descriptors) from a directory authority, if
            // any.
            ConsensusBoundData::Verified {
                consensus,
                ttl,
                futile,
            } => {
                // See if there are any missing descriptors that are not Refused
                // yet.  It is important to not exclude the NotFound descriptors
                // here because they may be available at a different authority.
                //
                // TODO DIRMIRROR: What to do in the case there is no authority
                // left in our list of endpoints?  Right now, this module of the
                // code is not aware of the endpoints to try and it is the
                // responsibility of the caller to check this.  Perhaps we
                // should provide a possibility to force hibernate, as in passing
                // an Option<DownloadAuthority> or an empty list.  An alternative
                // worth exploring might also be to perform the RetryDelay
                // wait logic, as in to not let the caller perform any timeouts
                // themselves.  Either way, we want to wait to hibernate and
                // wait for the next consensus in the case that no authority
                // is left.
                //
                // TODO DIRMIRROR: This appears to be prone to copy and paste
                // errors, we should do something about it, as in macros and/or
                // traits.
                let (missing_routers, missing_micros, missing_extras) = (
                    consensus.missing_routers(tx, futile.routers.refused(), Some(1))?,
                    consensus.missing_micros(tx, futile.micros.refused(), Some(1))?,
                    consensus.missing_extras(tx, futile.extras.refused(), Some(1))?,
                );

                if *ttl <= now {
                    // The ttl has been surpassed, download a new
                    // consensus.  It is very important TO NOT transition to
                    // State::LoadConsensus here, because the current consensus
                    // may still be valid but not fresh anymore, in which case
                    // State::LoadConsensus will continue to obtain it from the
                    // database until valid-after has been surpassed, which is
                    // most definitely not what we want.
                    State::FetchConsensus
                } else if missing_routers.is_empty()
                    && missing_micros.is_empty()
                    && missing_extras.is_empty()
                {
                    // All queues are empty, meaning we are done, until ttl
                    // ends.
                    State::Hibernate
                } else {
                    // The ttl has not been surpassed and we have stuff
                    // to download, so we need to obtain the descriptors.
                    State::Descriptors
                }
            }
        };
        Ok(state)
    }

    /// Executes a single state iteration in the finite state machine.
    ///
    /// The return value is of type [`Result<(), OperationError>`].
    /// The success type is not of much interest for calling applications.
    /// However, the error case itself should be passed towards
    /// [`crate::err::IsFatal::is_fatal()`] in order to either abort the
    /// application or retry with an appropriate timeout.
    ///
    // TODO: Use tracing instrumentation here.
    // TODO DIRMIRROR: Document the state transition check which we have to do
    // because of database invariances no longer holding true.
    async fn execute<R: Rng>(
        &self,
        pool: &Pool<SqliteConnectionManager>,
        data: &mut ConsensusBoundData<T>,
        endpoint: &DownloadAuthority,
        now: Timestamp,
        rng: &mut R,
    ) -> Result<(), OperationError> {
        // TODO DIRMIRROR: Right now, we pass around the pool object which is
        // not very nice.  Instead, we should match based on the following
        // criteria: Needs write transaction, needs read transaction, needs
        // pool, needs no database access.

        // TODO: Should we return DatabaseError or something like
        // StateDeterminationError?  Either way, both cases should be seriously
        // fatal.
        let state = db::read_tx(pool, |tx| self.determine_state(tx, data, now))??;
        debug!("state is {state}");

        match state {
            State::LoadConsensus => self.load_consensus(pool, data, now, rng),
            State::FetchConsensus => Ok(self.fetch_consensus(data, endpoint, now).await?),
            State::AuthCerts => self.auth_certs(pool, data, endpoint, now).await,
            State::StoreConsensus => self.store_consensus(pool, data, now),
            State::Descriptors => self.descriptors(pool, data, endpoint, now).await,
            State::Hibernate => self.hibernate(data, now).await,
        }
    }

    /// Executes [`State::LoadConsensus`].
    ///
    /// This method does the following:
    /// * Load the most recent valid consensus from the database.
    /// * Compute the ttl for it.
    /// * Compute the missing descriptors for it.
    fn load_consensus<R: Rng>(
        &self,
        pool: &Pool<SqliteConnectionManager>,
        data: &mut ConsensusBoundData<T>,
        now: Timestamp,
        rng: &mut R,
    ) -> Result<(), OperationError> {
        // Load the most recent valid consensus from the database.
        //
        // If there is no consensus, we should have not entered the state, which
        // means that the database must have been externally verified.
        // In this case, it is probably better to return a bug, as external
        // applications arbitrarily modifying the database while we are running
        // leaves too much room for wrong/weird behavior.
        let consensus = db::read_tx(pool, |tx| self.recent_consensus(tx, now))??
            .ok_or_else(|| internal!("database externally modified?"))?;
        let ttl = consensus.ttl(rng);
        let futile = Box::new(FutileDescriptors::default());

        *data = ConsensusBoundData::Verified {
            consensus,
            ttl,
            futile,
        };
        Ok(())
    }

    /// Fetches a consensus from an upstream authority.
    // TODO DIRMIRROR: Add logging.
    #[allow(clippy::string_slice)] // TODO
    async fn fetch_consensus(
        &self,
        data: &mut ConsensusBoundData<T>,
        endpoint: &DownloadAuthority,
        now: Timestamp,
    ) -> Result<(), AuthorityRequestError> {
        // Obtain the consensus.
        let (raw, consensus) = self
            .send_request(endpoint, ConsensusRequest::new(T::flavor()))
            .await?;
        let mut consensus = consensus.into_iter().collect::<VecDeque<_>>();

        // Check for the correct number of results.
        if consensus.len() != 1 {
            return Err(AuthorityRequestError::Response(
                "invalid number of consensus?",
            ));
        }
        let (consensus, start, end) = match consensus.pop_front().expect("pop failed?") {
            (Ok(consensus), start, end) => (consensus, start, end),
            // We do not mark unparseable consensuses as futile because they
            // cannot be referenced in a semi-unique fashion but rather depend
            // on the time only.
            //
            // TODO DIRMIRROR: Return a more descriptive error; ideally in
            // all places where only one document was returned and that document
            // failed to parse.
            (Err(_), _, _) => {
                return Err(AuthorityRequestError::Response(
                    "invalid consensus received",
                ));
            }
        };
        let raw = raw[start..end].to_string();

        let ttl = now + UNVERIFIED_TTL;

        // And store it.
        *data = ConsensusBoundData::Unverified {
            consensus,
            raw,
            ttl,
        };

        Ok(())
    }

    /// Fetches, validates, and stores authority certificates.
    #[allow(clippy::string_slice)] // TODO
    async fn auth_certs(
        &self,
        pool: &Pool<SqliteConnectionManager>,
        data: &mut ConsensusBoundData<T>,
        endpoint: &DownloadAuthority,
        now: Timestamp,
    ) -> Result<(), OperationError> {
        let certs_already = db::read_tx(pool, |tx| self.certs_already(tx, now))??;

        // Obtain the missing authority certificate identifiers.
        let missing = match data {
            ConsensusBoundData::Unverified { consensus, .. } => {
                match consensus.can_verify(self.authorities.v3idents(), &certs_already) {
                    Err(ConsensusVerifiabilityError::MissingAuthCerts { missing, .. }) => missing,
                    _ => return Err(OperationError::Bug(internal!("we have all auth certs"))),
                }
            }
            _ => return Err(OperationError::Bug(internal!("data is not unverified"))),
        };

        // Compose the request.
        let mut requ = AuthCertRequest::new();
        for kp in missing.iter().copied() {
            requ.push(kp);
        }

        // Fire it off.
        let (resp, certs) = self
            .send_request::<_, AuthCertUnverified>(endpoint, requ)
            .await?;

        // Verify each certificate.  Invalid certificates and other problems get
        // logged and filtered out, with the result being then inserted into
        // the database.
        let certs = certs
            .into_iter()
            .filter_map(|(unverified, start, end)| {
                let unverified = match unverified {
                    Ok(v) => v,
                    Err(e) => {
                        // We do not mark unparseable authority certificates as
                        // futile because they do not have an authoritative
                        // digest we could ad-hoc compare them against.
                        debug!("ignoring invalid authority certificate: {e}");
                        return None;
                    }
                };
                let kp = unverified.inspect_unverified().0.key_ids();

                // Skip certificates we did not asked for.
                //
                // Not much of an issue because certificate verification will
                // usually fail anyways, except for this weird edge-case where we
                // actually have that id fingerprint in the v3idents.
                if !missing.contains(&kp) {
                    debug!("authority returned certificate we did not asked for: {kp:?}");
                    return None;
                }

                let verified = match unverified.verify(self.authorities.v3idents()) {
                    Ok(c) => c,
                    Err(e) => {
                        debug!("received invalid auth cert ({kp:?}): {e}");
                        return None;
                    }
                };

                let timely = match self
                    .tolerance
                    .extend_tolerance(verified)
                    .if_valid_at(&now.into())
                {
                    Ok(c) => c,
                    Err(e) => {
                        debug!("received non-timely auth cert ({kp:?}): {e}");
                        return None;
                    }
                };

                Some((timely, &resp[start..end]))
            })
            .collect::<Vec<_>>();

        // When we have reached this, it means that this call made no progress,
        // i.e. the authority only returned certificates we were not interested
        // in.
        if certs.is_empty() {
            Err(AuthorityRequestError::NoRequestedDocumentsReturned)?;
        }

        // Finally, insert them all into the database.
        db::rw_tx(pool, |tx| {
            for (cert, data) in certs {
                AuthCertMeta::insert(tx, self.encodings.iter().copied(), &cert, data)?;
            }
            Ok::<_, DatabaseError>(())
        })??;

        Ok(())
    }

    /// Verifies a consensus and inserts it into the database.
    fn store_consensus(
        &self,
        pool: &Pool<SqliteConnectionManager>,
        data: &mut ConsensusBoundData<T>,
        now: Timestamp,
    ) -> Result<(), OperationError> {
        // It is fine to replace data with ConsensusBoundData::None because in
        // both cases, the following state of this will always be LoadConsensus
        // or FetchConsensus, both of them no longer requiring the previous data.
        //
        // Yes, we want to explicitly discard this in the case of a recoverable
        // error in order to retry again by fetching a new consensus from a
        // different authority.
        let (unverified, raw) = match mem::replace(data, ConsensusBoundData::None) {
            ConsensusBoundData::Unverified { consensus, raw, .. } => (consensus, raw),
            _ => return Err(OperationError::Bug(internal!("data is not unverified"))),
        };

        // TODO DIRMIRROR: Somewhere in here, we should generate the consensus
        // diffs.  However, this is a CPU intensive task and needs further
        // coordination with the orport developers.  See arti#2706

        db::rw_tx(pool, |tx| {
            let certs_already = self.certs_already(tx, now)?;
            let (verified, sigs) = self.verify_consensus(unverified, &certs_already, now)?;
            ConsensusMeta::<T>::insert(
                tx,
                self.encodings.iter().copied(),
                (&verified, &sigs),
                &raw,
            )?;
            Ok::<_, OperationError>(())
        })?
    }

    /// Downloads, verifies, and inserts the descriptors associated with the
    /// currently served consensus.
    async fn descriptors(
        &self,
        pool: &Pool<SqliteConnectionManager>,
        data: &mut ConsensusBoundData<T>,
        endpoint: &DownloadAuthority,
        now: Timestamp,
    ) -> Result<(), OperationError> {
        match T::flavor() {
            ConsensusFlavor::Plain => {
                // TODO DIRMIRROR: Add extras.
                self.descriptors_rd(pool, data, endpoint, now).await
            }
            ConsensusFlavor::Microdesc => self.descriptors_md(pool, data, endpoint, now).await,
        }
    }

    /// Router descriptor part of [`StaticEngine::descriptors()`].
    async fn descriptors_rd(
        &self,
        pool: &Pool<SqliteConnectionManager>,
        data: &mut ConsensusBoundData<T>,
        endpoint: &DownloadAuthority,
        now: Timestamp,
    ) -> Result<(), OperationError> {
        debug_assert_eq!(T::flavor(), ConsensusFlavor::Plain);
        self.descriptors_agnostic::<RdDownloader>(pool, data, endpoint, now)
            .await
    }

    /// Micro descriptor part of [`StaticEngine::descriptors()`].
    async fn descriptors_md(
        &self,
        pool: &Pool<SqliteConnectionManager>,
        data: &mut ConsensusBoundData<T>,
        endpoint: &DownloadAuthority,
        now: Timestamp,
    ) -> Result<(), OperationError> {
        debug_assert_eq!(T::flavor(), ConsensusFlavor::Microdesc);
        self.descriptors_agnostic::<MdDownloader>(pool, data, endpoint, now)
            .await
    }

    /// Descriptor flavor agnostic engine driving the download, verification,
    /// and insertion of descriptors using [`DescriptorDownloader`].
    async fn descriptors_agnostic<D: DescriptorDownloader<T>>(
        &self,
        pool: &Pool<SqliteConnectionManager>,
        data: &mut ConsensusBoundData<T>,
        endpoint: &DownloadAuthority,
        now: Timestamp,
    ) -> Result<(), OperationError> {
        let (meta, futile) = match data {
            ConsensusBoundData::Verified {
                consensus, futile, ..
            } => (consensus, futile),
            _ => return Err(OperationError::Bug(internal!("data not verified"))),
        };

        // Obtain the missing descriptors.
        let descriptors = db::read_tx(pool, |tx| D::query(tx, meta, futile, endpoint))??;
        if descriptors.is_empty() {
            // This is equivalent to sending off an empty request and failing
            // afterwards because no progress was made, but it saves us
            // bandwidth by not doing a redundant HTTP request.  We may enter
            // this branch if there are no descriptors left that are not marked
            // as not found or refused, in which case we must try the next
            // authority as it may have the not found descriptors.
            debug!("not downloading any descriptors");
            Err(OperationError::AuthorityRequest(
                AuthorityRequestError::NoRequestedDocumentsReturned,
            ))?;
        }

        debug!("downloading the following descriptors: {descriptors:?}");
        let requ = D::make_request(&descriptors);
        let (raw, docs) = self.send_request::<_, D::Response>(endpoint, requ).await?;

        // Verify each descriptor.
        // Process all downloads isolated, so that we do not return early
        // on accident.  While we still have one minor exception below with
        // regard to DatabaseError, that one is well documented.
        let downloads = DescriptorDownloads::from_missing(descriptors.into_iter());
        let downloads = D::process_downloads(self, downloads, docs, raw, now);

        // Determine if we made progress by checking whether we have any
        // descriptors that are either found or refused.  If this is the case,
        // we will return later, once the descriptors are marked as such.
        let progress = downloads
            .values()
            .find(|x| !matches!(x, DescriptorDownloadResult::NotFound))
            .map(|_| ()); // Do not borrow.

        // Insert the obtained descriptors in one large bulk transaction or
        // mark them as futile.
        //
        // It is okay if we fail before setting the descriptors as futile here,
        // because database failures are pretty much irrecoverable anyways.
        // Doing this together in the same loop saves us from having to
        // filter and split the large HashMap into multiple ones.  It should be
        // secure because the inner closure has the return error type of
        // DatabaseError, meaning only these fatal errors can return early.
        db::rw_tx(pool, |tx| D::insert(self, tx, futile, downloads, endpoint))??;

        // If no progress, return with an error.  We can do so here because
        // we have finally marked descriptors as futile.
        if progress.is_none() {
            Err(OperationError::AuthorityRequest(
                AuthorityRequestError::NoRequestedDocumentsReturned,
            ))?;
        }

        Ok(())
    }

    /// Hibernates for the remaining ttl of the consensus.
    async fn hibernate(
        &self,
        data: &mut ConsensusBoundData<T>,
        now: Timestamp,
    ) -> Result<(), OperationError> {
        match data {
            ConsensusBoundData::None => {
                return Err(internal!("hibernating without a consensus?").into());
            }
            // TODO DIRMIRROR: Should the Unverified case be an error or a
            // success? In other words: Should we exclude the current authority
            // from the set of the next authorities to try?
            ConsensusBoundData::Verified { ttl, .. }
            | ConsensusBoundData::Unverified { ttl, .. } => {
                let timeout = *ttl - now;
                debug!("hibernating for {}s", timeout.as_secs());
                tokio::time::sleep(timeout).await;
            }
        }

        Ok(())
    }

    /// Convenience wrapper around [`tor_dirclient::send_request()`].
    ///
    /// It opens a TCP connection, performs the request, and parses the result.
    ///
    /// Returns the raw response alongside the output of
    /// [`parse2::parse_netdoc_multiple_sophisticated()`].
    ///
    /// An important distinction towards [`tor_dirclient::send_request()`] is,
    /// that we do not consider an empty response or a 404 response as an error.
    /// Instead, we just return [`Ok`] with an empty [`String`] and an empty
    /// [`Vec`] instead.  The reason for this is, that the futile document
    /// strategy (i.e. determing which documents of the request are missing)
    /// should be the same for responses containing zero (requested) documents
    /// and responses containing at least one but less than the number of
    /// the originally requested documents.
    ///
    /// The output is required because we need the raw document alongside the
    /// offsets to have the actual data we will insert into the database later
    /// on.
    async fn send_request<R: Requestable, D: NetdocParseable>(
        &self,
        endpoint: &DownloadAuthority,
        requ: R,
    ) -> Result<(String, Vec<(Result<D, ParseError>, usize, usize)>), AuthorityRequestError> {
        // The check is required to not let Tokio panic.
        if endpoint.is_empty() {
            return Err(AuthorityRequestError::Bug(internal!("empty endpoint?")));
        }

        // Open the TCP connection.
        let mut stream = TcpStream::connect(endpoint)
            .await
            .map_err(AuthorityRequestError::TcpConnect)?
            .compat();

        // Perform the request and map the result nicely.
        let resp = tor_dirclient::send_request(&self.rt, &requ, &mut stream, None)
            .await
            .map(|resp| {
                resp.output_string()
                    .map(|resp| resp.to_owned())
                    // Allows us to flatten the result.
                    .map_err(tor_dirclient::Error::from)
            });

        // We can immediately drop the connection now, no need to occupy even
        // more resources from the authority.  Doing so is fine, it is HTTP/1.0
        // and there is no connection reuse anyways.
        drop(stream);

        // Non-trivial error handling strategy explained in the rustdoc comment
        // above.
        let resp = match resp.flatten() {
            Ok(resp) => Ok(resp),

            // This error might actually be Ok in certain cases.
            Err(DirClientError::RequestFailed(
                ref outer @ RequestFailedError {
                    error: ref inner, ..
                },
            )) => match inner {
                // If one of these errors occurs, do not fail but rather return
                // no documents.
                RequestError::EmptyRequest => {
                    warn!("we should not send an empty request");
                    return Ok(Default::default());
                }
                RequestError::EmptyResponse | RequestError::HttpStatus(404, _) => {
                    return Ok(Default::default());
                }

                // All other errors imply an underlying error with the
                // respective endpoint, suggesting a switch.
                _ => Err(outer.clone().into()),
            },

            // Should not happen because the other DirClientErrors are either
            // Bug or related to CircMgr, which we do not use.
            Err(e) => Err(AuthorityRequestError::Bug(internal!(
                "unhandled dirclient error: {e}"
            ))),
        }?;

        // Parse the response.
        let parsed = parse2::parse_netdoc_multiple_sophisticated(&ParseInput::new(&resp, ""))?;

        Ok((resp, parsed))
    }

    /// Queries and validates the most recent consensus from the database.
    ///
    /// Effectively a wrapper around [`StaticEngine::verify_consensus()`] with
    /// the data obtained from the database.
    fn recent_consensus(
        &self,
        tx: &Transaction<'_>,
        now: Timestamp,
    ) -> Result<Option<ConsensusMeta<T>>, DatabaseError> {
        let meta = match ConsensusMeta::<T>::query(tx)?.as_slice() {
            &[front] | &[front, ..] => front,
            &[] => return Ok(None),
        };
        let raw = meta.data(tx)?;

        let unverified = match parse2::parse_netdoc::<T>(&ParseInput::new(&raw, "<database>")) {
            Ok(unverified) => unverified,
            Err(e) => {
                // TODO DIRMIRROR: Perhaps we should remove it?
                debug!("unparseable consensus in database: {meta:?} {e}");
                return Ok(None);
            }
        };

        let certs_already = self.certs_already(tx, now)?;

        match self.verify_consensus(unverified, &certs_already, now) {
            Ok(_) => Ok(Some(meta)),
            Err(e) => {
                // TODO DIRMIRROR: Perhaps we should remove it?
                debug!("ignoring invalid consensus in database: {meta:?} {e}");
                Ok(None)
            }
        }
    }

    /// Parses and verifies a raw consensus in a database agnostic fashion.
    fn verify_consensus(
        &self,
        unverified: T,
        certs_already: &[AuthCert],
        now: Timestamp,
    ) -> Result<(T::Body, T::Signatures), VerifyFailed> {
        let sigs = unverified.sigs().clone();

        let verified = unverified.verify(self.authorities.v3idents(), certs_already)?;

        self.tolerance
            .extend_tolerance(verified)
            .if_valid_at(&now.into())
            .map(|body| (body, sigs))
            .map_err(|e| e.into())
    }

    /// Loads all authority certificates from the database into a [`Vec<AuthCert>`].
    ///
    /// Performance wise, it is quite inefficient as it parses and verifies all
    /// certificates over again.  However, this should be fine as the N for
    /// directory authorities is usually very small.
    fn certs_already(
        &self,
        tx: &Transaction<'_>,
        now: Timestamp,
    ) -> Result<Vec<AuthCert>, DatabaseError> {
        let raw_certs = AuthCertMeta::query(tx)?
            .into_iter()
            .map(|meta| Ok::<_, DatabaseError>((meta, meta.data(tx)?)))
            .collect::<Result<Vec<_>, _>>()?;

        let mut certs_already = Vec::new();
        for (meta, raw) in raw_certs {
            // Only used for debugging.
            // TODO DIRMIRROR: Put this into span with tracing.
            let key_ids = AuthCertKeyIds {
                id_fingerprint: meta.kp_auth_id_rsa_sha1.0.into(),
                sk_fingerprint: meta.kp_auth_sign_rsa_sha1.0.into(),
            };

            let unverified = match parse2::parse_netdoc::<AuthCertUnverified>(&ParseInput::new(
                &raw,
                "<database>",
            )) {
                Ok(c) => c,
                Err(e) => {
                    // TODO DIRMIRROR: Perhaps we should remove it?
                    debug!("unparseable auth cert ({key_ids:?}) in database: {e}");
                    continue;
                }
            };

            let verified = match unverified.verify(self.authorities.v3idents()) {
                Ok(c) => c,
                Err(e) => {
                    debug!("ignoring invalid auth cert ({key_ids:?}): {e}");
                    continue;
                }
            };

            let timely = match self
                .tolerance
                .extend_tolerance(verified)
                .if_valid_at(&now.into())
            {
                Ok(c) => c,
                Err(e) => {
                    debug!("ignoring non-timely auth cert ({key_ids:?}): {e}");
                    continue;
                }
            };
            certs_already.push(timely);
        }
        Ok(certs_already)
    }
}

/// Helper trait for reducing the copy and paste we have to do in the
/// [`StaticEngine::descriptors`] method, as parts of the logic overlap a lot
/// between router and micro descriptors.
trait DescriptorDownloader<T: FlavoredConsensusUnverified> {
    /// The document digest by which we query the respective descriptors.
    type DocDigest: Debug + Hash + Eq + Clone + Copy;

    /// The actual descriptor type we are working with.
    type Descriptor: FlavoredDescriptor;

    /// The [`tor_dirclient`] request data type we are emitting.
    type Request: Requestable;

    /// The response data type we expect from the dirserver we are contacting.
    type Response: NetdocParseable;

    /// Queries the database for the missing descriptor document digests
    /// contained within a [`HashSet`].
    ///
    /// This is usually just a wrapper around [`ConsensusMeta::missing_routers()`]
    /// and similar methods.
    fn query(
        tx: &Transaction<'_>,
        meta: &ConsensusMeta<T>,
        futile: &FutileDescriptors,
        endpoint: &DownloadAuthority,
    ) -> Result<HashSet<Self::DocDigest>, DatabaseError>;

    /// Creates a [`Requestable`] from the missing descriptors returned through
    /// [`Self::query()`].
    fn make_request(digests: &HashSet<Self::DocDigest>) -> Self::Request;

    /// Processes the response after it has been received.
    ///
    /// It's inputs are a [`DescriptorDownloads`] that contains all the
    /// requested digests set to [`DescriptorDownloadResult::NotFound`].
    ///
    /// The purpose of this function is to populate this struct accordingly and
    /// return it in the end.  The function itself must not fail, hence why
    /// it does not return a Result.
    fn process_downloads(
        engine: &StaticEngine<T>,
        downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
        docs: Vec<(Result<Self::Response, ParseError>, usize, usize)>,
        raw: String,
        now: Timestamp,
    ) -> DescriptorDownloads<Self::DocDigest, Self::Descriptor>;

    /// Finally, insert all descriptors either into the database or populate
    /// [`FutileDescriptors`] accordingly.  This function may still leave the
    /// [`FutileDescriptors`] in an inconsistent state, but only in the case
    /// of an irrecoverable [`DatabaseError`], which is ok.
    fn insert(
        engine: &StaticEngine<T>,
        tx: &Transaction<'_>,
        futile: &mut FutileDescriptors,
        downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
        endpoint: &DownloadAuthority,
    ) -> Result<(), DatabaseError>;
}

/// Common implementation of [`DescriptorDownloader::insert()`].
///
/// Signature is almost identical to the respective origianl one, except that it
/// additionally accepts a function item that returns the respective
/// [`FutileDescriptorSet`] item out of [`FutileDescriptors`]; this is to avoid
/// duplication.
// TODO: Once we have extra-info support, consider moving this implementation
// into the trait method.
fn downloader_common_insert<T: FlavoredConsensusUnverified, D: DescriptorDownloader<T>>(
    engine: &StaticEngine<T>,
    tx: &Transaction<'_>,
    futile: &mut FutileDescriptors,
    downloads: DescriptorDownloads<D::DocDigest, D::Descriptor>,
    endpoint: &DownloadAuthority,
    get_futile: fn(&mut FutileDescriptors) -> &mut FutileDescriptorSet<D::DocDigest>,
) -> Result<(), DatabaseError> {
    for (digest, res) in downloads.into_iter() {
        match res {
            DescriptorDownloadResult::NotFound => {
                get_futile(futile).set_not_found(digest, endpoint);
            }
            DescriptorDownloadResult::Refused => get_futile(futile).set_refused(digest),
            DescriptorDownloadResult::Found(descriptor, raw) => {
                DescriptorMeta::insert(tx, engine.encodings.iter().copied(), &descriptor, &raw)?;
            }
        }
    }
    Ok(())
}

/// Unit type implementing [`DescriptorDownloader`] for router descriptors.
struct RdDownloader;

impl<T: FlavoredConsensusUnverified> DescriptorDownloader<T> for RdDownloader {
    type DocDigest = Sha1;
    type Descriptor = FlavoredDescriptorPlain;
    type Request = RouterDescRequest;
    type Response = RouterDescUnverified;

    fn query(
        tx: &Transaction<'_>,
        meta: &ConsensusMeta<T>,
        futile: &FutileDescriptors,
        endpoint: &DownloadAuthority,
    ) -> Result<HashSet<Self::DocDigest>, DatabaseError> {
        meta.missing_routers(tx, futile.routers.excluded(endpoint), DESCRIPTOR_LIMIT)
    }

    fn make_request(digests: &HashSet<Self::DocDigest>) -> Self::Request {
        RouterDescRequest::from_iter(digests.iter().map(|sha1| sha1.0))
    }

    fn process_downloads(
        engine: &StaticEngine<T>,
        mut downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
        docs: Vec<(Result<Self::Response, ParseError>, usize, usize)>,
        raw: String,
        now: Timestamp,
    ) -> DescriptorDownloads<Self::DocDigest, Self::Descriptor> {
        for (unverified, start, end) in docs {
            let Ok(unverified) = unverified else {
                // TODO DIRMIRROR: Handle parser failures as potentially futile.
                //
                // This is going to be a big can of worms, because in the case
                // of a parser failure, we must check whether the part between
                // "router" and "router-signature" matches the digest of a
                // requested descriptor, while checking that the body and
                // signature parts of the document alone parse just fine.
                //
                // body_ok && signature_ok => the parser has not failed, unreachable
                // body_ok && !signature_ok => not futile
                // !body_ok && signature_ok => futile
                // !body_ok && !signature_ok => futile
                //
                // (with ok meaning that the parser suceeded, no statement
                // of cryptographic validity is being made here)
                //
                // The `RoutereDescUnverifiedParsedBody as NetdocParseable`
                // pattern may be useful for this check.
                continue;
            };

            // Defensive internal checks.
            let Some(raw) = raw.get(start..end) else {
                warn!("parse2 returned invalid string slice: {start}..{end}");
                continue;
            };
            let raw = raw.to_string();
            let Some(sha1) = unverified.sigs.hashes.sha1 else {
                warn!("accumulator contains no SHA-1?");
                continue;
            };
            let sha1 = Sha1(sha1);

            // Checks whether the response is weird, as in containing
            // unrequested or duplicate descriptors.
            match downloads.get(&sha1) {
                Some(DescriptorDownloadResult::NotFound) => {}
                Some(DescriptorDownloadResult::Found(_, _) | DescriptorDownloadResult::Refused) => {
                    debug!("{sha1:?} contained multiple times in response");
                    continue;
                }
                None => {
                    debug!("ignoring unrequested router descriptor: {sha1:?}");
                    continue;
                }
            };

            // Perform the relevant cryptographic checks.
            let sigs = unverified.sigs.clone();
            let verified = match unverified.verify() {
                Ok(verified) => verified,
                Err(e) => {
                    // Continuing here implicitly marks the descriptor as not
                    // found after the loop ends.
                    debug!("ignoring invalid router descriptor: {sha1:?}: {e}");
                    continue;
                }
            };
            let timely = match engine
                .tolerance
                .extend_tolerance(verified)
                .if_valid_at(&now.into())
            {
                Ok(timely) => timely,
                Err(e) => {
                    // Untimely is considered as refused for the lifespan of the
                    // current consensus.
                    debug!("ignoring untimely router descriptor: {sha1:?}: {e}");
                    let prev = downloads.insert(sha1, DescriptorDownloadResult::Refused);
                    debug_assert!(matches!(prev, Some(DescriptorDownloadResult::NotFound)));
                    continue;
                }
            };

            let prev = downloads.insert(sha1, DescriptorDownloadResult::Found((timely, sigs), raw));
            debug_assert!(matches!(prev, Some(DescriptorDownloadResult::NotFound)));
        }
        downloads
    }

    fn insert(
        engine: &StaticEngine<T>,
        tx: &Transaction<'_>,
        futile: &mut FutileDescriptors,
        downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
        endpoint: &DownloadAuthority,
    ) -> Result<(), DatabaseError> {
        downloader_common_insert::<T, RdDownloader>(
            engine,
            tx,
            futile,
            downloads,
            endpoint,
            |futile| &mut futile.routers,
        )
    }
}

/// Unit type implementing [`DescriptorDownloader`] for micro descriptors.
struct MdDownloader;

impl<T: FlavoredConsensusUnverified> DescriptorDownloader<T> for MdDownloader {
    type DocDigest = Sha256;
    type Descriptor = FlavoredDescriptorMd;
    type Request = MicrodescRequest;
    type Response = Microdesc;

    fn query(
        tx: &Transaction<'_>,
        meta: &ConsensusMeta<T>,
        futile: &FutileDescriptors,
        endpoint: &DownloadAuthority,
    ) -> Result<HashSet<Self::DocDigest>, DatabaseError> {
        meta.missing_micros(tx, futile.micros.excluded(endpoint), DESCRIPTOR_LIMIT)
    }

    fn make_request(digests: &HashSet<Self::DocDigest>) -> Self::Request {
        MicrodescRequest::from_iter(digests.iter().map(|sha256| sha256.0))
    }

    fn process_downloads(
        _engine: &StaticEngine<T>,
        mut downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
        docs: Vec<(Result<Self::Response, ParseError>, usize, usize)>,
        raw: String,
        _now: Timestamp,
    ) -> DescriptorDownloads<Self::DocDigest, Self::Descriptor> {
        for (md, start, end) in docs {
            // Defensive internal check.
            let Some(raw) = raw.get(start..end) else {
                warn!("parse2 returned invalid string slice: {start}..{end}");
                continue;
            };
            let raw = raw.to_string();

            // Calculate the SHA-256 over the entire document; we can do this
            // before accessing the parsed result.
            let sha256 = Sha256::digest(raw.as_bytes());
            match downloads.get(&sha256) {
                Some(DescriptorDownloadResult::NotFound) => {}
                Some(DescriptorDownloadResult::Found(_, _) | DescriptorDownloadResult::Refused) => {
                    debug!("{sha256:?} contained multiple times in response");
                    continue;
                }
                None => {
                    debug!("ignoring unrequested micro descriptor: {sha256:?}");
                    continue;
                }
            }

            // Check whether the parsing was successful in the first place.
            // If not, we mark the descriptor as refused, because we have
            // implicitly verified it's cryptographic integrity above through
            // the digest.
            let Ok(md) = md else {
                let prev = downloads.insert(sha256, DescriptorDownloadResult::Refused);
                debug_assert!(matches!(prev, Some(DescriptorDownloadResult::NotFound)));
                continue;
            };

            let sha1 = Sha1::digest(raw.as_bytes());
            let prev = downloads.insert(
                sha256,
                DescriptorDownloadResult::Found((md, sha1, sha256), raw),
            );
            debug_assert!(matches!(prev, Some(DescriptorDownloadResult::NotFound)));
        }
        downloads
    }

    fn insert(
        engine: &StaticEngine<T>,
        tx: &Transaction<'_>,
        futile: &mut FutileDescriptors,
        downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
        endpoint: &DownloadAuthority,
    ) -> Result<(), DatabaseError> {
        downloader_common_insert::<T, MdDownloader>(
            engine,
            tx,
            futile,
            downloads,
            endpoint,
            |futile| &mut futile.micros,
        )
    }
}

/// Records which allow us to avoid futile download attempts
///
/// One set of records of "futile" documents, for each kind of document.
#[derive(Debug, Clone, Default)]
struct FutileDescriptors {
    /// The futile router descriptors.
    routers: FutileDescriptorSet<Sha1>,

    /// The futile extra-infos.
    extras: FutileDescriptorSet<Sha1>,

    /// The futile micro descriptors.
    micros: FutileDescriptorSet<Sha256>,
}

/// A generic struct storing which document are futile for which reason.
///
/// A document is "futile" if there is no point retrying its download.
/// More precisely,
///
///   * We note which authorities didn't have a document when we tried to download it.
///     This avoids us trying that same document again, uselessly.
// TODO DIRMIRROR but what if the authority acquires the document in the meantime?
//
///   * We note the hashes of documents we couldn't parse.
///     If the hash matched, but the parse failed, there is no point trying to get
///     this document at all because the same hash means the same document
///     and therefore the same parse error.
// TODO: Right now, we allow a value to be present in both: not_found and refused.
// Do we want to allow this or should we potentially change the representation
// similar to the way we are doing it in DescriptorDownloadResult?  Not blocking,
// as a hazard here is not the end of the world, but solving it may be more
// elegant.
#[derive(Educe)]
#[educe(Debug, Clone, Default)]
struct FutileDescriptorSet<T: Debug + Clone + Copy + Eq + Hash> {
    /// The descriptors that are not found on a given endpoint.
    not_found: HashSet<(T, Box<DownloadAuthority>)>,
    /// The descriptor that are outright refused.
    refused: HashSet<T>,
}

impl<T: Debug + Clone + Copy + Eq + Hash> FutileDescriptorSet<T> {
    /// Returns an iterator over the digest that are not found.
    fn not_found(&self, endpoint: &DownloadAuthority) -> impl Iterator<Item = T> {
        self.not_found
            .iter()
            .filter(|(_, this_endpoint)| **this_endpoint == *endpoint)
            .map(|(d, _)| *d)
    }

    /// Returns an iterator over the digest that are refused.
    fn refused(&self) -> impl Iterator<Item = T> {
        self.refused.iter().copied()
    }

    /// Chaining of `.not_found()` and `.refused()`.
    fn excluded(&self, endpoint: &DownloadAuthority) -> impl Iterator<Item = T> {
        self.not_found(endpoint).chain(self.refused())
    }

    /// Marks a digest in combination with an authority as not found.
    fn set_not_found(&mut self, digest: T, endpoint: &DownloadAuthority) {
        self.not_found.insert((digest, endpoint.into()));
    }

    /// Marks a digest as refused.
    fn set_refused(&mut self, digest: T) {
        self.refused.insert(digest);
    }
}

/// Intermediate data structure for storing the result of a downloaded
/// descriptor within a batch of downloads.
///
/// Populated before the insertion into [`FutileDescriptors`] takes place,
/// so that the actual population of [`FutileDescriptors`] remains atomic.
#[derive(Debug, Clone)]
enum DescriptorDownloadResult<D: FlavoredDescriptor> {
    /// The descriptor was found and verified.
    Found(D, String),
    /// The descriptor was not found; implicit default.
    NotFound,
    /// We do not accept this descriptor.
    Refused,
}

/// Collection of [`DescriptorDownloadResult`] values indexed by their digest.
///
/// Used during downloading a batch in order to atomically update
/// [`FutileDescriptors`].
#[derive(Debug, Clone, derive_more::Deref, derive_more::DerefMut, derive_more::IntoIterator)]
struct DescriptorDownloads<K, D: FlavoredDescriptor>(HashMap<K, DescriptorDownloadResult<D>>);

impl<K: Eq + Hash, D: FlavoredDescriptor> DescriptorDownloads<K, D> {
    /// Creates a [`DescriptorDownloads`] from a set of all missing descriptors.
    ///
    /// The idea is to call this right after the database call and before
    /// any downloads are actually being made, as it initializes the data
    /// structure with all the keys to [`DescriptorDownloadResult::NotFound`].
    fn from_missing(digests: impl Iterator<Item = K>) -> Self {
        Self(
            digests
                .map(|digest| (digest, DescriptorDownloadResult::NotFound))
                .collect(),
        )
    }
}

#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    #![allow(clippy::string_slice)] // See arti#2571
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->

    use std::{collections::HashSet, iter};

    use rusqlite::params;
    use strum::IntoEnumIterator;
    use tokio::{
        io::{AsyncReadExt, AsyncWriteExt},
        net::TcpListener,
    };
    use tor_basic_utils::test_rng::testing_rng;

    use crate::{database::sql, testdata2};

    use super::*;

    type Plain = tor_netdoc::doc::netstatus::plain::NetworkStatusUnverified;
    type Md = tor_netdoc::doc::netstatus::md::NetworkStatusUnverified;

    /// Returns a [`StaticEngine`] for testing.
    fn static_engine<T>() -> StaticEngine<T> {
        StaticEngine {
            authorities: testdata2::current_auth_cert_contacts(),
            tolerance: DirTolerance::default(),
            rt: PreferredRuntime::current().unwrap(),
            encodings: ContentEncoding::iter().collect(),
            _phantom: Default::default(),
        }
    }

    /// Tests whether the load consensus state computes missing descriptors
    /// properly.
    ///
    /// For this, the test removes a present router descriptor from the storage
    /// to verify that it is detected as missing and added to the download
    /// queue.
    #[tokio::test]
    async fn state_load_consensus() {
        let pool = testdata2::test_db();
        let mut data = ConsensusBoundData::<Plain>::None;
        let engine = static_engine();

        let time: Timestamp = testdata2::valid_system_time().into();
        let fresh_until: Timestamp = testdata2::current_consensus_ns()
            .0
            .preamble
            .lifetime
            .fresh_until
            .0
            .into();
        let valid_until: Timestamp = testdata2::current_consensus_ns()
            .0
            .preamble
            .lifetime
            .valid_until
            .0
            .into();
        // This is the middle of valid_until and fresh_until.
        let fresh_until_half = fresh_until + ((valid_until - fresh_until) / 2);

        // Remove a single router descriptor from our storage to see whether it
        // appears in the download queue as expected.
        let relay_to_remove = &testdata2::current_consensus_ns().0.routers[0];
        let relay_to_remove = db::Sha1::from(*relay_to_remove.doc_digest());
        pool.get()
            .unwrap()
            .execute(
                sql!("DELETE FROM descriptor WHERE sha1 = ?1"),
                params![relay_to_remove],
            )
            .unwrap();

        engine
            .load_consensus(&pool, &mut data, time, &mut testing_rng())
            .unwrap();

        // El-cheapo assert_eq due to lack of PartialEq for tor-netdoc poc.
        match data {
            ConsensusBoundData::Verified { consensus, ttl, .. } => {
                // If everything worked properly, then the queue should only
                // contain the relay we removed, because that is missing now.
                db::read_tx(&pool, |tx| {
                    assert_eq!(
                        consensus.missing_routers(tx, iter::empty(), None).unwrap(),
                        HashSet::from([relay_to_remove])
                    );
                    assert!(
                        consensus
                            .missing_extras(tx, iter::empty(), None)
                            .unwrap()
                            .is_empty()
                    );
                    assert!(
                        consensus
                            .missing_micros(tx, iter::empty(), None)
                            .unwrap()
                            .is_empty()
                    );
                })
                .unwrap();
                assert!(ttl >= fresh_until);
                assert!(ttl <= fresh_until_half);
            }
            _ => panic!("data is not verified"),
        }
    }

    /// Tests whether the fetch consensus state properly fetches a consensus
    /// and keeps it in memory as unverified.
    ///
    /// For this, we spawn a tokio task simulating a web server which responds
    /// with a consensus.
    #[tokio::test]
    async fn state_fetch_consensus() {
        let pool = testdata2::test_db();
        let mut data = ConsensusBoundData::<Plain>::None;
        let engine = static_engine();
        let now = Timestamp::from(testdata2::invalid_system_time());

        let state = db::read_tx(&pool, |tx| engine.determine_state(tx, &data, now))
            .unwrap()
            .unwrap();
        assert_eq!(state, State::FetchConsensus);

        let server = TcpListener::bind("[::1]:0").await.unwrap();
        let saddr = server.local_addr().unwrap();
        tokio::spawn(async move {
            let (mut stream, _) = server.accept().await.unwrap();
            let mut buf = vec![0; 1024];
            let _ = stream.read(&mut buf).await.unwrap();

            let consensus = testdata2::current_consensus_ns().2;
            let resp = format!(
                "HTTP/1.0 200 OK\r\nContent-Encoding: identity\r\nContent-Length: {}\r\n\r\n{consensus}",
                consensus.len()
            );
            stream.write_all(resp.as_bytes()).await.unwrap();
        });

        engine
            .fetch_consensus(&mut data, &[saddr], now)
            .await
            .unwrap();
        match data {
            ConsensusBoundData::Unverified { raw, ttl, .. } => {
                assert_eq!(raw, testdata2::current_consensus_ns().2);
                assert_eq!(ttl, now + UNVERIFIED_TTL);
            }
            _ => panic!("data is not unverified"),
        }
    }

    /// Tests the download, verification, and insertion of authority certificates.
    ///
    /// For this, it starts by removing an existing one from the test database
    /// to see it getting re-downloaded, re-verified, and re-inserted again.
    #[tokio::test]
    async fn state_auth_certs() {
        let pool = testdata2::test_db();
        let mut data = ConsensusBoundData::<Plain>::Unverified {
            consensus: parse2::parse_netdoc(&ParseInput::new(
                testdata2::current_consensus_ns().2,
                "",
            ))
            .unwrap(),
            raw: testdata2::current_consensus_ns().2.to_owned(),
            ttl: Timestamp::from(testdata2::valid_system_time()) + UNVERIFIED_TTL,
        };
        let mut engine = static_engine();

        // We want to download authority certificates; for this, remove
        // one of them from the database.
        pool.get()
            .unwrap()
            .execute(
                sql!(
                    "
                    DELETE FROM authority_key_certificate
                    WHERE :kp_auth_id_rsa_sha1 = ?1
                    "
                ),
                params![db::Sha1::from(
                    testdata2::current_auth_cert_ids()[0].to_bytes()
                )],
            )
            .unwrap();

        assert_eq!(
            db::read_tx(&pool, |tx| engine.determine_state(
                tx,
                &data,
                testdata2::valid_system_time().into()
            ))
            .unwrap()
            .unwrap(),
            State::AuthCerts
        );

        let server = TcpListener::bind("[::1]:0").await.unwrap();
        let saddr = server.local_addr().unwrap();
        tokio::spawn(async move {
            let mut buf = [0; 1024];
            let (mut stream, _) = server.accept().await.unwrap();
            let _ = stream.read(&mut buf).await.unwrap();

            let authcerts = testdata2::current_auth_certs()
                .into_iter()
                .map(|x| x.1)
                .collect::<String>();

            stream.write_all(format!(
                "HTTP/1.0 200 OK\r\nContent-Encoding: identity\r\nContent-Length: {}\r\n\r\n{authcerts}",
                authcerts.len()
            ).as_bytes()).await.unwrap();
        });

        // Fetch all authcerts.
        engine
            .auth_certs(
                &pool,
                &mut data,
                &[saddr],
                testdata2::valid_system_time().into(),
            )
            .await
            .unwrap();

        // Check whether we are done with all authcerts.
        assert_eq!(
            db::read_tx(&pool, |tx| engine.determine_state(
                tx,
                &data,
                testdata2::valid_system_time().into(),
            ))
            .unwrap()
            .unwrap(),
            State::StoreConsensus
        );
        // Check whether we now have all auth certs in the database.
        let certs = db::read_tx(&pool, |tx| {
            engine.certs_already(tx, testdata2::valid_system_time().into())
        })
        .unwrap()
        .unwrap();

        let got = certs
            .into_iter()
            .map(|c| c.dir_identity_key.to_rsa_identity())
            .collect::<HashSet<_>>();
        let expect = engine.authorities.v3idents().iter().copied().collect();
        assert_eq!(got, expect);

        // Check an edge case of not having enough trusted signers.
        engine.authorities = AuthorityContacts::builder().build().unwrap();
        let state = db::read_tx(&pool, |tx| {
            engine.determine_state(tx, &data, testdata2::valid_system_time().into())
        })
        .unwrap()
        .unwrap();
        assert_eq!(state, State::Hibernate);
    }

    /// Checks whether we can probably load and parse all certificates from
    /// the database.
    #[tokio::test]
    async fn certs_already() {
        let pool = testdata2::test_db();
        let engine = static_engine::<Plain>();

        db::read_tx(&pool, |tx| {
            // With a correct system time, this should align with all authority
            // fingerprints we have.
            let certs_already = engine
                .certs_already(tx, testdata2::valid_system_time().into())
                .unwrap();
            assert_eq!(certs_already.len(), engine.authorities.v3idents().len());
            assert!(certs_already.iter().all(|c| {
                engine
                    .authorities
                    .v3idents()
                    .contains(&c.dir_identity_key.to_rsa_identity())
            }));

            // With an invalid system time, it should be empty.
            let certs_already = engine
                .certs_already(tx, testdata2::invalid_system_time().into())
                .unwrap();
            assert!(certs_already.is_empty());
        })
        .unwrap();
    }

    /// Ensures that an unverified consensus gets properly inserted into the
    /// database.
    #[tokio::test]
    async fn state_store_consensus() {
        let pool = testdata2::test_db();
        let unverified: Plain =
            parse2::parse_netdoc(&ParseInput::new(testdata2::current_consensus_ns().2, ""))
                .unwrap();
        let engine = static_engine();
        let now = Timestamp::from(testdata2::valid_system_time());
        let mut data = ConsensusBoundData::<Plain>::Unverified {
            consensus: unverified.clone(),
            raw: testdata2::current_consensus_ns().2.to_string(),
            ttl: now + UNVERIFIED_TTL,
        };

        // Clean all consensus related tables.
        pool.get()
            .unwrap()
            .execute_batch(sql!(
                "
                DELETE FROM consensus_descriptor_member;
                DELETE FROM consensus_authority_voter;
                DELETE FROM consensus;
                "
            ))
            .unwrap();

        // Execute the StoreConsensus state.
        let state = db::read_tx(&pool, |tx| engine.determine_state(tx, &data, now))
            .unwrap()
            .unwrap();
        assert_eq!(state, State::StoreConsensus);
        engine.store_consensus(&pool, &mut data, now).unwrap();
        assert!(matches!(&data, ConsensusBoundData::None));

        // Verify that it got inserted.
        let state = db::read_tx(&pool, |tx| engine.determine_state(tx, &data, now))
            .unwrap()
            .unwrap();
        assert_eq!(state, State::LoadConsensus);
        engine
            .load_consensus(&pool, &mut data, now, &mut testing_rng())
            .unwrap();
        assert!(matches!(data, ConsensusBoundData::Verified { .. }));
    }

    /// Agnostic test for the descriptor state.
    async fn state_descriptors_agnostic<
        T: FlavoredConsensusUnverified,
        D: DescriptorDownloader<T>,
    >(
        descriptors: Vec<String>,
        get_futile: fn(&FutileDescriptors) -> &FutileDescriptorSet<D::DocDigest>,
    ) {
        let pool = testdata2::test_db();
        let engine = static_engine::<T>();
        let now = Timestamp::from(testdata2::valid_system_time());
        let mut data = ConsensusBoundData::None;
        let rng = &mut testing_rng();

        // Server task that can at most handle two requests.
        //
        // The first response contains all available descriptors
        // statically, whereas the second one only contains a single
        // descriptor.
        let listener = TcpListener::bind("[::1]:0").await.unwrap();
        let endpoint = listener.local_addr().unwrap();
        tokio::spawn(async move {
            let mut buf = [0; 1024];
            let full = descriptors.iter().cloned().collect::<String>();
            let single = descriptors.iter().take(1).cloned().collect::<String>();

            let (mut stream, _) = listener.accept().await.unwrap();
            let _ = stream.read(&mut buf).await.unwrap();
            stream
                .write_all(
                    format!(
                        "HTTP/1.0 200 OK\r\nContent-Length: {}\r\n\r\n{}",
                        full.len(),
                        full
                    )
                    .as_bytes(),
                )
                .await
                .unwrap();
            drop(stream);

            let (mut stream, _) = listener.accept().await.unwrap();
            let _ = stream.read(&mut buf).await.unwrap();
            stream
                .write_all(
                    format!(
                        "HTTP/1.0 200 OK\r\nContent-Length: {}\r\n\r\n{}",
                        single.len(),
                        single
                    )
                    .as_bytes(),
                )
                .await
                .unwrap();
        });

        // Delete all descriptors from the database and then load
        // a consensus into ConsensusBoundData.
        db::rw_tx(&pool, |tx| tx.execute(sql!("DELETE FROM descriptor"), ()))
            .unwrap()
            .unwrap();
        engine.load_consensus(&pool, &mut data, now, rng).unwrap();
        let state = db::read_tx(&pool, |tx| engine.determine_state(tx, &data, now))
            .unwrap()
            .unwrap();
        assert_eq!(state, State::Descriptors);

        // Successful bootstrap of all descriptors.
        engine
            .descriptors(&pool, &mut data, &[endpoint], now)
            .await
            .unwrap();

        // Afterwards, the queue for missing descriptors should be empty
        // as well as futile.
        let (meta, futile) = match &data {
            ConsensusBoundData::Verified {
                consensus: meta,
                futile,
                ..
            } => (*meta, futile.clone()),
            _ => panic!(),
        };
        let missing = db::read_tx(&pool, |tx| D::query(tx, &meta, &futile, &[endpoint]))
            .unwrap()
            .unwrap();
        assert!(missing.is_empty());
        assert!(get_futile(&futile).not_found.is_empty());
        assert!(get_futile(&futile).refused.is_empty());

        // Now, if we do this again, futile should be populated.
        db::rw_tx(&pool, |tx| tx.execute(sql!("DELETE FROM descriptor"), ()))
            .unwrap()
            .unwrap();

        // Because this time the server will only return a single descriptor,
        // it may either succeed or fail because it returned a descriptor that
        // we did not asked for.  Either way, it does not really matter because
        // we want to test whether the remaining ones get set as missing or not,
        // which is done in the next step.
        let res = engine.descriptors(&pool, &mut data, &[endpoint], now).await;
        assert!(matches!(
            res,
            Ok(())
                | Err(OperationError::AuthorityRequest(
                    AuthorityRequestError::NoRequestedDocumentsReturned
                ))
        ));

        // Now, the missing descriptors should equal the ones that were not
        // found on the authority, as in being in the futile set.
        let missing = db::read_tx(&pool, |tx| D::query(tx, &meta, &futile, &[endpoint]))
            .unwrap()
            .unwrap();
        let futile = match &data {
            ConsensusBoundData::Verified { futile, .. } => futile,
            _ => panic!(),
        };
        assert!(!missing.is_empty());
        assert_eq!(
            missing,
            get_futile(futile)
                .not_found
                .iter()
                .filter_map(|(digest, this_endpoint)| if **this_endpoint == [endpoint] {
                    Some(*digest)
                } else {
                    None
                })
                .collect::<HashSet<_>>()
        );
        assert!(get_futile(futile).refused.is_empty());
    }

    /// Tests the descriptor bootstrapping for router descriptors.
    #[tokio::test]
    async fn state_descriptors_plain() {
        state_descriptors_agnostic::<Plain, RdDownloader>(
            testdata2::current_router_descs()
                .into_iter()
                .map(|(_, _, raw)| raw)
                .collect(),
            |futile| &futile.routers,
        )
        .await;
    }

    #[tokio::test]
    async fn state_descriptors_md() {
        state_descriptors_agnostic::<Md, MdDownloader>(
            testdata2::current_micro_descs()
                .into_iter()
                .map(|(_, raw)| raw)
                .collect(),
            |futile| &futile.micros,
        )
        .await;
    }
}