1mod dir_source;
52mod rs;
53
54pub mod md;
55pub mod plain;
56pub mod vote;
57
58#[cfg(feature = "build_docs")]
59mod build;
60
61pub use proto_statuses_parse2_encode::ProtoStatusesNetdocParseAccumulator;
62
63use crate::doc::authcert::EncodedAuthCert;
64
65use crate::doc::authcert::{self, AuthCert, AuthCertKeyIds, AuthCertUnverified};
66use crate::encode::{
67 EncodeOrd, ItemArgument, ItemEncoder, ItemValueEncodable, NetdocEncodable, NetdocEncoder,
68};
69use crate::parse::keyword::Keyword;
70use crate::parse::parser::{Section, SectionRules, SectionRulesBuilder};
71use crate::parse::tokenize::{Item, ItemResult, NetDocReader};
72use crate::parse2::{
73 self, ArgumentError, ArgumentStream, ErrorProblem, IsStructural, ItemArgumentParseable,
74 ItemStream, ItemValueParseable, KeywordRef, NetdocParseable, NetdocParseableUnverified,
75 SignatureHashInputs, SignatureItemParseable, StopAt, UnparsedItem, VerifyFailed,
76};
77use crate::types::relay_flags::{self, DocRelayFlags};
78use crate::types::{self, *};
79use crate::util::PeekableIterator;
80use crate::{Error, KeywordEncodable, NetdocErrorKind as EK, NormalItemArgument, Pos};
81use std::collections::{BTreeSet, HashMap, HashSet};
82use std::fmt::{self, Display};
83use std::slice;
84use std::str::FromStr;
85use std::sync::Arc;
86use std::time::{self, SystemTime};
87use std::{net, result};
88use tor_basic_utils::iter_join;
89use tor_error::{Bug, HasKind, bad_api_usage, internal};
90use tor_protover::Protocols;
91use void::ResultVoidExt as _;
92
93use derive_deftly::{Deftly, define_derive_deftly};
94use digest::Digest;
95use educe::Educe;
96use itertools::Itertools;
97use saturating_time::SaturatingTime as _;
98use std::sync::LazyLock;
99use tor_checkable::{ExternallySigned, TimeBound, timed::TimeRangeBound};
100use tor_llcrypto as ll;
101use tor_llcrypto::pk::rsa::RsaIdentity;
102
103use serde::{Deserialize, Deserializer};
104
105#[cfg(feature = "build_docs")]
106pub use build::MdConsensusBuilder;
107#[cfg(feature = "build_docs")]
108pub use build::PlainConsensusBuilder;
109#[cfg(feature = "build_docs")]
110ns_export_each_flavor! {
111 ty: RouterStatusBuilder;
112}
113
114ns_export_each_variety! {
115 ty: Footer, RouterStatus, Preamble;
116}
117
118#[deprecated]
119pub use PlainConsensus as NsConsensus;
120#[deprecated]
121pub use PlainRouterStatus as NsRouterStatus;
122#[deprecated]
123pub use UncheckedPlainConsensus as UncheckedNsConsensus;
124#[deprecated]
125pub use UnvalidatedPlainConsensus as UnvalidatedNsConsensus;
126
127#[deprecated]
128pub use InvalidRelayBandwidth as InvalidRelayWeights;
129#[deprecated]
130pub use RelayBandwidth as RelayWeight;
131#[deprecated]
132pub use RelayBandwidthItem as RelayWeightsItem;
133#[deprecated]
134pub use VoteRelayBandwidthItem as VoteRelayWeightsItem;
135
136pub use rs::{RouterStatusMdDigestsVote, RouterStatusMdDigestsVoteConstructor, SoftwareVersion};
137
138pub use dir_source::{
139 ConsensusAuthoritySection, ConsensusAuthoritySectionConstructor, DirSource,
140 DirSourceConstructor, SupersededAuthorityKey,
141};
142
143define_constant_string! {
144 NetworkStatusVersion = "3";
154}
155
156define_constant_string! {
157 VoteStatusConsensus = "consensus";
161}
162
163define_constant_string! {
164 VoteStatusVote = "vote";
168}
169
170#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Default)]
184#[allow(clippy::exhaustive_structs)]
185pub struct IgnoredPublicationTimeSp;
186
187#[derive(Clone, Debug, PartialEq, Eq, Deftly)]
195#[derive_deftly(Constructor, NetdocEncodableFields, NetdocParseableFields)]
196#[derive_deftly(Lifetime)]
197#[allow(clippy::exhaustive_structs)]
198pub struct Lifetime {
199 #[deftly(constructor)]
206 #[deftly(netdoc(single_arg))]
207 pub valid_after: Iso8601TimeSp,
208 #[deftly(constructor)]
216 #[deftly(netdoc(single_arg))]
217 pub fresh_until: Iso8601TimeSp,
218 #[deftly(constructor)]
226 #[deftly(netdoc(single_arg))]
227 pub valid_until: Iso8601TimeSp,
228
229 #[doc(hidden)]
230 #[deftly(netdoc(skip))]
231 pub __non_exhaustive: (),
232}
233
234define_derive_deftly! {
235 Lifetime:
237
238 ${defcond FIELD not(approx_equal($fname, __non_exhaustive))}
239
240 impl Lifetime {
241 pub fn new(
243 $( ${when FIELD} $fname: time::SystemTime, )
244 ) -> crate::Result<Self> {
245 let self_ = Lifetime {
249 $( ${when FIELD} $fname: $fname.into(), )
250 __non_exhaustive: (),
251 };
252 if self_.valid_after < self_.fresh_until && self_.fresh_until < self_.valid_until {
253 Ok(self_)
254 } else {
255 Err(EK::InvalidLifetime.err())
256 }
257 }
258 $(
259 ${when FIELD}
260
261 ${fattrs doc}
262 pub fn $fname(&self) -> time::SystemTime {
263 *self.$fname
264 }
265 )
266 pub fn valid_at(&self, when: time::SystemTime) -> bool {
268 *self.valid_after <= when && when <= *self.valid_until
269 }
270
271 pub fn voting_period(&self) -> time::Duration {
276 let valid_after = self.valid_after();
277 let fresh_until = self.fresh_until();
278 fresh_until
279 .duration_since(valid_after)
280 .expect("Mis-formed lifetime")
281 }
282 }
283}
284use derive_deftly_template_Lifetime;
285
286#[derive(Debug, Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Copy)] #[derive(derive_more::From, derive_more::Into, derive_more::Display, derive_more::FromStr)]
298#[allow(clippy::exhaustive_structs)] pub struct ConsensusMethod(pub u32);
300impl NormalItemArgument for ConsensusMethod {}
301
302#[derive(Debug, Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Deftly)] #[derive(derive_more::Into, derive_more::From, derive_more::Deref)]
312#[derive_deftly(ItemValueEncodable, ItemValueParseable)]
313#[allow(clippy::exhaustive_structs)]
314pub struct ConsensusMethods {
315 pub methods: BTreeSet<ConsensusMethod>,
317}
318
319pub mod consensus_methods_comma_separated {
324 use super::*;
325 use parse2::ArgumentError as AE;
326 use std::result::Result;
327
328 pub fn from_args<'s>(args: &mut ArgumentStream<'s>) -> Result<ConsensusMethods, AE> {
330 let mut methods = BTreeSet::new();
331 for ent in args.next().ok_or(AE::Missing)?.split(',') {
332 let ent = ent.parse().map_err(|_| AE::Invalid)?;
333 if !methods.insert(ent) {
334 return Err(AE::Invalid);
335 }
336 }
337 Ok(ConsensusMethods { methods })
338 }
339
340 pub fn write_arg_onto(self_: &ConsensusMethods, out: &mut ItemEncoder) -> Result<(), Bug> {
342 out.args_raw_string(&iter_join(",", &self_.methods));
343 Ok(())
344 }
345}
346
347#[derive(Debug, Clone, Eq, PartialEq, Hash, Copy, Deftly)]
351#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
352#[allow(clippy::exhaustive_structs)]
353pub struct VotingDelay {
354 #[deftly(constructor)]
356 pub vote_seconds: u32,
357
358 #[deftly(constructor)]
360 pub dist_seconds: u32,
361
362 #[doc(hidden)]
363 #[deftly(netdoc(skip))]
364 pub __non_exhaustive: (),
365}
366
367pub type NetParamValues = ParamValues<i32>;
377
378#[derive(Debug, Clone, Educe, Eq, PartialEq)]
431#[educe(Default)]
432pub struct ParamValues<T> {
433 params: HashMap<String, T>,
435}
436
437impl<T> ParamValues<T> {
438 #[allow(unused)]
440 pub fn new() -> Self {
441 ParamValues::default()
442 }
443 pub fn get<A: AsRef<str>>(&self, v: A) -> Option<&T> {
447 self.params.get(v.as_ref())
448 }
449 pub fn iter(&self) -> impl Iterator<Item = (&String, &T)> {
451 self.params.iter()
452 }
453 pub fn set(&mut self, k: String, v: T) {
458 self.params.insert(k, v);
459 }
460 pub fn clear(&mut self, k: &str) {
466 self.params.remove(k);
467 }
468}
469
470impl<K: Into<String>, T> FromIterator<(K, T)> for ParamValues<T> {
471 fn from_iter<I: IntoIterator<Item = (K, T)>>(i: I) -> Self {
472 ParamValues {
473 params: i.into_iter().map(|(k, v)| (k.into(), v)).collect(),
474 }
475 }
476}
477
478impl<T> std::iter::Extend<(String, T)> for ParamValues<T> {
479 fn extend<I: IntoIterator<Item = (String, T)>>(&mut self, iter: I) {
480 self.params.extend(iter);
481 }
482}
483
484impl<'de, T> Deserialize<'de> for ParamValues<T>
485where
486 T: Deserialize<'de>,
487{
488 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
489 where
490 D: Deserializer<'de>,
491 {
492 let params = HashMap::deserialize(deserializer)?;
493 Ok(ParamValues { params })
494 }
495}
496
497#[derive(Debug, Clone, Educe, Eq, PartialEq, derive_more::From, derive_more::FromStr)]
511#[educe(Default)]
512pub struct NetParams {
513 params: NetParamValues,
515}
516
517impl NetParams {
518 pub fn without_defaults(&self) -> &NetParamValues {
524 &self.params
525 }
526
527 pub fn into_without_defaults(self) -> NetParamValues {
533 self.params
534 }
535
536 pub fn set(&mut self, k: String, v: i32) {
540 self.params.set(k, v);
541 }
542
543 pub fn clear(&mut self, k: &str) {
550 self.params.clear(k);
551 }
552}
553
554impl<K: Into<String>> FromIterator<(K, i32)> for NetParams {
555 fn from_iter<I: IntoIterator<Item = (K, i32)>>(i: I) -> Self {
556 NetParams {
557 params: i.into_iter().collect(),
558 }
559 }
560}
561
562#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize, Deftly)]
571#[derive_deftly(Constructor)]
572#[allow(clippy::exhaustive_structs)]
573pub struct ProtoStatus {
574 pub recommended: Protocols,
579
580 pub required: Protocols,
585
586 #[doc(hidden)]
587 #[serde(skip)]
588 pub __non_exhaustive: (),
589}
590
591impl ProtoStatus {
592 pub fn check_protocols(
602 &self,
603 supported_protocols: &Protocols,
604 ) -> Result<(), ProtocolSupportError> {
605 let missing_required = self.required.difference(supported_protocols);
607 if !missing_required.is_empty() {
608 return Err(ProtocolSupportError::MissingRequired(missing_required));
609 }
610 let missing_recommended = self.recommended.difference(supported_protocols);
611 if !missing_recommended.is_empty() {
612 return Err(ProtocolSupportError::MissingRecommended(
613 missing_recommended,
614 ));
615 }
616
617 Ok(())
618 }
619}
620
621#[derive(Clone, Debug, thiserror::Error)]
623#[cfg_attr(test, derive(PartialEq))]
624#[non_exhaustive]
625pub enum ProtocolSupportError {
626 #[error("Required protocols are not implemented: {0}")]
628 MissingRequired(Protocols),
629
630 #[error("Recommended protocols are not implemented: {0}")]
634 MissingRecommended(Protocols),
635}
636
637impl ProtocolSupportError {
638 pub fn should_shutdown(&self) -> bool {
640 matches!(self, Self::MissingRequired(_))
641 }
642}
643
644impl HasKind for ProtocolSupportError {
645 fn kind(&self) -> tor_error::ErrorKind {
646 tor_error::ErrorKind::SoftwareDeprecated
647 }
648}
649
650#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, Deftly)]
657#[derive_deftly(Constructor)]
658#[allow(clippy::exhaustive_structs)]
659pub struct ProtoStatuses {
660 pub client: ProtoStatus,
662
663 pub relay: ProtoStatus,
665
666 #[doc(hidden)]
667 #[serde(skip)]
668 pub __non_exhaustive: (),
669}
670
671impl ProtoStatuses {
672 pub fn client(&self) -> &ProtoStatus {
674 &self.client
675 }
676
677 pub fn relay(&self) -> &ProtoStatus {
679 &self.relay
680 }
681}
682
683#[derive(Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd)] #[derive(derive_more::Deref, derive_more::Into)]
704pub struct RecommendedTorVersions(BTreeSet<String>);
705
706#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
708#[non_exhaustive]
709pub enum InvalidRecommendedTorVersions {
710 #[error("version {_0:?} contains whitespace")]
712 ContainsWhitespace(String),
713
714 #[error("version {_0:?} is repeated")]
716 Repeated(String),
717}
718
719impl RecommendedTorVersions {
720 pub fn new_unknown() -> Self {
722 Self::default()
723 }
724
725 pub fn is_known(&self) -> bool {
731 !self.is_empty()
732 }
733
734 #[allow(clippy::should_implement_trait)] pub fn from_iter<I, S>(i: I) -> Result<Self, InvalidRecommendedTorVersions>
737 where
738 I: IntoIterator<Item = S>,
739 S: AsRef<str>,
740 {
741 let mut set = BTreeSet::new();
742 for v in i {
743 let v = v.as_ref();
744 if v.is_empty() {
745 continue;
746 }
747 if v.chars().any(|c| c.is_whitespace()) {
748 return Err(InvalidRecommendedTorVersions::ContainsWhitespace(
749 v.to_owned(),
750 ));
751 }
752 if !set.insert(v.to_owned()) {
753 return Err(InvalidRecommendedTorVersions::Repeated(v.to_owned()));
754 }
755 }
756 Ok(RecommendedTorVersions(set))
757 }
758}
759
760impl FromStr for RecommendedTorVersions {
761 type Err = InvalidRecommendedTorVersions;
762 fn from_str(s: &str) -> Result<Self, InvalidRecommendedTorVersions> {
763 Self::from_iter(s.split(','))
764 }
765}
766
767impl Display for RecommendedTorVersions {
768 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
769 write!(f, "{}", iter_join(",", &self.0))
770 }
771}
772
773impl NormalItemArgument for RecommendedTorVersions {}
774
775impl ItemValueEncodable for RecommendedTorVersions {
776 fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
777 out.args_raw_string(self);
778 Ok(())
779 }
780}
781
782impl ItemValueParseable for RecommendedTorVersions {
783 fn from_unparsed(mut item: UnparsedItem) -> Result<Self, ErrorProblem> {
784 const FIELD: &str = "versions";
785 item.check_no_object()?;
786 let args = item.args_mut();
787 let arg = args.next().unwrap_or("");
788 arg.parse::<Self>()
789 .map_err(|_| args.handle_error(FIELD, ArgumentError::Invalid))
790 }
791}
792
793#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
801#[allow(clippy::exhaustive_enums)]
802pub enum ConsensusFlavor {
803 Microdesc,
806 Plain,
811}
812
813impl ConsensusFlavor {
814 pub fn name(&self) -> &'static str {
816 match self {
817 ConsensusFlavor::Plain => "ns", ConsensusFlavor::Microdesc => "microdesc",
819 }
820 }
821 pub fn from_opt_name(name: Option<&str>) -> crate::Result<Self> {
826 match name {
827 Some("microdesc") => Ok(ConsensusFlavor::Microdesc),
828 Some("ns") | None => Ok(ConsensusFlavor::Plain),
829 Some(other) => {
830 Err(EK::BadDocumentType.with_msg(format!("unrecognized flavor {:?}", other)))
831 }
832 }
833 }
834}
835
836define_derive_deftly! {
837 DirectorySignaturesHashesAccu:
845
846 ${define FNAME ${paste ${snake_case $vname}} }
847
848 #[derive(Clone, Copy, Default, Debug, Eq, PartialEq, Deftly)]
850 #[derive_deftly(AsMutSelf)]
851 #[non_exhaustive]
852 pub struct DirectorySignaturesHashesAccu {
853 $(
854 ${vattrs doc}
855 pub $FNAME: Option<[u8; ${vmeta(hash_len) as expr}]>,
856 )
857 }
858
859 impl DirectorySignaturesHashesAccu {
860 fn update_from(
862 &mut self,
863 algo: &DigestAlgoInSignature,
864 body: &SignatureHashInputs,
865 ) {
866 ${define HASH {
869 self.$UPDATE.get_or_insert_with(|| {
871 let mut h = tor_llcrypto::d::$ALGO::new();
872 h.update(body.body().body());
873 h.update(body.signature_item_kw_spc);
874 h.finalize().into()
875 });
876 }}
877
878 match &**algo {
879 $(
880 Some(KeywordOrString::Known($vtype)) => {
881 ${define UPDATE $FNAME}
882 ${define ALGO $vname}
883 $HASH
884 }
885 )
886 None => {
887 ${define UPDATE sha1}
888 ${define ALGO Sha1}
889 $HASH
890 }
891 Some(KeywordOrString::Unknown(..)) => {}
892 }
893 }
894
895 fn hash_slice(
900 &self,
901 algo: &DigestAlgoInSignature,
902 ) -> Option<&[u8]> {
903 match &**algo {
904 $(
905 Some(KeywordOrString::Known($vtype)) => Some(self.$FNAME.as_ref()?),
906 )
907 None => Some(self.sha1.as_ref()?),
908 Some(KeywordOrString::Unknown(..)) => None,
909 }
910 }
911 }
912}
913
914#[derive(Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, Deftly)]
916#[derive_deftly(DirectorySignaturesHashesAccu)]
917#[non_exhaustive]
918#[strum(serialize_all = "snake_case")]
919pub enum DirectorySignatureHashAlgo {
920 #[deftly(hash_len = "20")]
922 Sha1,
923 #[deftly(hash_len = "32")]
925 Sha256,
926}
927
928#[derive(Debug, Clone, derive_more::Deref, derive_more::DerefMut)]
940#[allow(clippy::exhaustive_structs)]
941pub struct DigestAlgoInSignature(pub Option<KeywordOrString<DirectorySignatureHashAlgo>>);
942
943impl ItemArgumentParseable for DigestAlgoInSignature {
944 fn from_args<'s>(args: &mut ArgumentStream<'s>) -> Result<Self, ArgumentError> {
945 let v = if args
946 .clone()
947 .next()
948 .and_then(|s| s.chars().all(|c| c.is_ascii_hexdigit()).then_some(()))
952 .is_some()
953 {
954 None
956 } else {
957 Some(KeywordOrString::from_args(args)?)
958 };
959 Ok(DigestAlgoInSignature(v))
960 }
961}
962impl ItemArgument for DigestAlgoInSignature {
963 fn write_arg_onto(&self, out: &mut ItemEncoder<'_>) -> Result<(), Bug> {
964 if let Some(y) = &self.0 {
965 y.write_arg_onto(out)?;
966 }
967 Ok(())
968 }
969}
970impl DigestAlgoInSignature {
971 pub fn algorithm(&self) -> &KeywordOrString<DirectorySignatureHashAlgo> {
975 self.as_ref()
976 .unwrap_or(&KeywordOrString::Known(DirectorySignatureHashAlgo::Sha1))
977 }
978}
979
980impl DigestAlgoInSignature {
981 pub fn from_algo(algo: DirectorySignatureHashAlgo) -> Self {
983 DigestAlgoInSignature(match algo {
984 DirectorySignatureHashAlgo::Sha1 => None,
985 other => Some(KeywordOrString::Known(other)),
986 })
987 }
988}
989
990impl From<DirectorySignatureHashAlgo> for DigestAlgoInSignature {
991 fn from(algo: DirectorySignatureHashAlgo) -> Self {
992 Self::from_algo(algo)
993 }
994}
995
996impl NormalItemArgument for DirectorySignatureHashAlgo {}
997
998#[derive(Debug, Clone, Deftly)]
1003#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
1004#[allow(clippy::exhaustive_structs)]
1005pub struct Signature {
1006 #[deftly(constructor)]
1011 pub digest_algo: DigestAlgoInSignature,
1012
1013 #[deftly(netdoc(with = authcert::keyids_directory_signature_args))]
1016 #[deftly(constructor)]
1017 pub key_ids: AuthCertKeyIds,
1018
1019 #[deftly(netdoc(object(label = "SIGNATURE"), with = types::raw_data_object))]
1021 #[deftly(constructor)]
1022 pub signature: Vec<u8>,
1023
1024 #[doc(hidden)]
1025 #[deftly(netdoc(skip))]
1026 pub __non_exhaustive: (),
1027}
1028
1029impl SignatureItemParseable for Signature {
1030 type HashAccu = DirectorySignaturesHashesAccu;
1031
1032 fn from_unparsed_and_body(
1033 item: UnparsedItem,
1034 body: &SignatureHashInputs<'_>,
1035 hash: &mut Self::HashAccu,
1036 ) -> Result<Self, ErrorProblem> {
1037 let signature = Signature::from_unparsed(item)?;
1038 hash.update_from(&signature.digest_algo, body);
1039 Ok(signature)
1040 }
1041}
1042
1043#[derive(Debug, thiserror::Error)]
1045#[non_exhaustive]
1046pub enum SigningError {
1047 #[error("signing netdoc: rsa")]
1049 Rsa(#[from] ll::pk::rsa::Error),
1050 #[error("signing netdoc: internal error")]
1052 Internal(#[from] Bug),
1053}
1054
1055impl Signature {
1056 pub fn sign_text(
1065 key: &ll::pk::rsa::KeyPair,
1066 text: &str,
1067 algo: DirectorySignatureHashAlgo,
1068 key_ids: AuthCertKeyIds,
1069 ) -> Result<Self, SigningError> {
1070 if key_ids.sk_fingerprint != key.to_public_key().to_rsa_identity() {
1075 Err(bad_api_usage!(
1076 "incorrect KP_auth_sign_rsa passed in to netdoc signing"
1077 ))?;
1078 }
1079
1080 let digest_algo = DigestAlgoInSignature::from_algo(algo);
1081
1082 let mut accu = DirectorySignaturesHashesAccu::default();
1083 accu.update_from(
1084 &digest_algo,
1085 &SignatureHashInputs::new_for_signature(text, "directory-signature "),
1086 );
1087 let hash_slice = accu
1088 .hash_slice(&digest_algo)
1089 .ok_or_else(|| internal!("somehow failed to record hash of the in-use algo"))?;
1090
1091 let signature = key.sign(hash_slice)?;
1092
1093 Ok(SignatureConstructor {
1094 digest_algo,
1095 key_ids,
1096 signature,
1097 }
1098 .construct())
1099 }
1100}
1101
1102#[derive(Debug, Clone)]
1108#[non_exhaustive]
1109pub struct SignatureGroup {
1110 pub hashes: DirectorySignaturesHashesAccu,
1116 pub signatures: Vec<Signature>,
1118}
1119
1120#[derive(Clone, Debug, thiserror::Error)]
1131#[allow(clippy::exhaustive_enums)]
1132pub enum ConsensusVerifiabilityError {
1133 #[error("consensus not signed by enough authorities")]
1135 InsufficientTrustedSigners,
1136
1137 #[error("missing auth certs mean we could not verify enough consensus signatures (need at least {deficit} more, out of {} that are missing)", missing.len())]
1139 MissingAuthCerts {
1140 deficit: usize,
1142 missing: HashSet<AuthCertKeyIds>,
1144 },
1145}
1146
1147#[derive(Clone, Debug, thiserror::Error)]
1159#[non_exhaustive]
1160pub enum ConsensusVerifyFailed {
1161 #[error("certs/sigs insufficient")]
1163 CertificationInsufficient(#[from] ConsensusVerifiabilityError),
1164
1165 #[error("invalid signature")]
1167 InvalidSignature(#[source] VerifyFailed),
1172}
1173
1174pub struct VoteVerifier {
1185 trusted: Vec<RsaIdentity>,
1187
1188 remaining_good: HashSet<RsaIdentity>,
1190}
1191
1192impl VoteVerifier {
1193 pub fn new(trusted: impl IntoIterator<Item = RsaIdentity>) -> Self {
1195 let trusted = trusted.into_iter().collect_vec();
1196 let remaining_good = trusted.iter().copied().collect();
1197 VoteVerifier {
1198 trusted,
1199 remaining_good,
1200 }
1201 }
1202}
1203
1204#[derive(Clone, Debug, thiserror::Error)]
1214#[non_exhaustive]
1215pub enum VoteVerifyFailed {
1216 #[error("invalid signature")]
1218 InvalidSignature(#[source] VerifyFailed),
1223
1224 #[error("unparseable authcert")]
1226 AuthCertParseError(#[source] parse2::ParseError),
1227
1228 #[error("authcert not valid for vote period")]
1230 AuthCertWrongValidity(#[source] tor_checkable::TimeValidityError),
1231
1232 #[error("wrong authcert")]
1234 AuthCertWrongAuthority,
1235
1236 #[error("duplicate authority {_0}")]
1240 DuplicateAuthority(RsaIdentity),
1241}
1242
1243#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)] #[derive(derive_more::From, derive_more::Into, derive_more::AsRef)]
1246pub struct SharedRandVal([u8; 32]);
1248
1249#[derive(Debug, Clone, Deftly, Eq, PartialEq, Hash)]
1252#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
1253#[allow(clippy::exhaustive_structs)]
1254pub struct SharedRandStatus {
1255 #[deftly(constructor)]
1257 pub n_reveals: u8,
1258
1259 #[deftly(constructor)]
1266 pub value: SharedRandVal,
1267
1268 pub timestamp: Option<Iso8601TimeNoSp>,
1272
1273 #[doc(hidden)]
1274 #[deftly(netdoc(skip))]
1275 pub __non_exhaustive: (),
1276}
1277
1278#[derive(Debug, Clone, Default, Deftly)]
1285#[derive_deftly(Constructor, NetdocEncodableFields, NetdocParseableFields)]
1286#[allow(clippy::exhaustive_structs)]
1287pub struct SharedRandStatuses {
1288 pub shared_rand_previous_value: Option<SharedRandStatus>,
1290
1291 pub shared_rand_current_value: Option<SharedRandStatus>,
1293
1294 #[doc(hidden)]
1295 #[deftly(netdoc(skip))]
1296 pub __non_exhaustive: (),
1297}
1298
1299#[derive(Debug, Clone)]
1356pub struct RelayBandwidthItem {
1357 effective: RelayBandwidth,
1359
1360 params: Unknown<Option<ParamValues<u32>>>,
1362}
1363
1364#[derive(Debug, Clone, Deftly)]
1366#[derive_deftly(NetdocEncodableFields, NetdocParseableFields)]
1367#[allow(clippy::exhaustive_structs)] pub struct VoteRelayBandwidthItem {
1369 pub w: Option<ParamValues<u32>>,
1371}
1372
1373#[non_exhaustive]
1377#[derive(Debug, Clone, Copy)]
1378pub enum RelayBandwidth {
1379 Unmeasured(u32),
1381 Measured(u32),
1383}
1384
1385#[derive(Debug, Clone, thiserror::Error)]
1387#[non_exhaustive]
1388pub enum InvalidRelayBandwidth {
1389 #[error("invalid value for Unmeasured")]
1391 InvalidUnmeasured,
1392}
1393
1394#[deprecated = "renamed to ConsensusAuthorityEntry"]
1396pub type ConsensusVoterInfo = ConsensusAuthorityEntry;
1397
1398pub type PlainAuthorityEntry = ConsensusAuthorityEntry;
1400pub type MdAuthorityEntry = ConsensusAuthorityEntry;
1402
1403#[derive(Debug, Clone, Deftly)]
1413#[derive_deftly(Constructor, NetdocEncodable, NetdocParseable)]
1414#[allow(clippy::exhaustive_structs)]
1415pub struct ConsensusAuthorityEntry {
1416 #[deftly(constructor)]
1418 pub dir_source: DirSource,
1419
1420 #[deftly(constructor)]
1426 pub contact: ContactInfo,
1427
1428 #[deftly(netdoc(single_arg))]
1435 #[deftly(constructor)]
1436 pub vote_digest: B16U,
1437
1438 #[doc(hidden)]
1439 #[deftly(netdoc(skip))]
1440 pub __non_exhaustive: (),
1441}
1442
1443#[derive(Debug, Clone, Deftly)]
1449#[derive_deftly(Constructor, NetdocEncodable, NetdocParseable)]
1450#[allow(clippy::exhaustive_structs)]
1451pub struct VoteAuthorityEntry {
1452 #[deftly(constructor)]
1454 pub dir_source: DirSource,
1455
1456 #[deftly(constructor)]
1458 pub contact: ContactInfo,
1459
1460 #[deftly(netdoc(single_arg))]
1464 pub legacy_dir_key: Option<Fingerprint>,
1465
1466 pub shared_rand_participate: Option<SharedRandParticipate>,
1470
1471 pub shared_rand_commit: Vec<SharedRandCommit>,
1475
1476 #[deftly(netdoc(flatten))]
1478 pub shared_rand: SharedRandStatuses,
1479
1480 #[doc(hidden)]
1481 #[deftly(netdoc(skip))]
1482 pub __non_exhaustive: (),
1483}
1484
1485#[derive(Debug, Clone, Deftly)]
1495#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
1496#[allow(clippy::exhaustive_structs)]
1497pub struct SharedRandParticipate {
1498 #[doc(hidden)]
1499 #[deftly(netdoc(skip))]
1500 pub __non_exhaustive: (),
1501}
1502
1503#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deftly)]
1507#[allow(clippy::exhaustive_enums)]
1509pub enum SharedRandCommit {
1510 V1(SharedRandCommitV1),
1512
1513 Unknown {},
1516}
1517
1518#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deftly)]
1527#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
1528#[allow(clippy::exhaustive_structs)]
1529pub struct SharedRandCommitV1 {
1530 #[deftly(constructor)]
1533 h_kp_auth_id_rsa: Fingerprint,
1534
1535 #[deftly(constructor)]
1543 commit: FixedB64<40>,
1544
1545 reveal: Option<FixedB64<40>>,
1550
1551 #[doc(hidden)]
1552 #[deftly(netdoc(skip))]
1553 pub __non_exhaustive: (),
1554}
1555
1556impl SharedRandCommitV1 {
1557 const FIXED_ARGUMENTS: &[&str] = &["1", "sha3-256"];
1559}
1560impl ItemValueEncodable for SharedRandCommit {
1561 fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
1562 match self {
1563 SharedRandCommit::V1(values) => {
1564 for fixed in SharedRandCommitV1::FIXED_ARGUMENTS {
1565 out.args_raw_string(fixed);
1566 }
1567 values.write_item_value_onto(out)
1568 }
1569 SharedRandCommit::Unknown {} => Err(internal!("encoding SharedRandCommit::Unknown")),
1570 }
1571 }
1572}
1573impl ItemValueParseable for SharedRandCommit {
1574 fn from_unparsed(mut item: UnparsedItem<'_>) -> Result<Self, ErrorProblem> {
1575 let mut fixed = SharedRandCommitV1::FIXED_ARGUMENTS.iter().copied();
1576 let args = item.args_mut();
1577 let version = args
1578 .next()
1579 .ok_or_else(|| args.handle_error("version", ArgumentError::Missing))?;
1580 if version != fixed.next().expect("nonempty") {
1581 return Ok(SharedRandCommit::Unknown {});
1582 }
1583 for exp in fixed {
1584 let got = args
1585 .next()
1586 .ok_or_else(|| args.handle_error(exp, ArgumentError::Missing))?;
1587 if got != exp {
1588 Err(args.handle_error(exp, ArgumentError::Invalid))?;
1589 }
1590 }
1591 let values = SharedRandCommitV1::from_unparsed(item)?;
1592 Ok(SharedRandCommit::V1(values))
1593 }
1594}
1595
1596define_derive_deftly! {
1599 VoteAuthoritySection:
1611
1612 ${defcond F_NORMAL not(fmeta(netdoc(skip)))}
1613
1614 impl NetdocParseable for VoteAuthoritySection {
1615 fn doctype_for_error() -> &'static str {
1616 "vote.authority.section"
1617 }
1618 fn is_intro_item_keyword(kw: KeywordRef<'_>) -> bool {
1619 VoteAuthorityEntry::is_intro_item_keyword(kw)
1620 }
1621 fn is_structural_keyword(kw: KeywordRef<'_>) -> Option<IsStructural> {
1622 $(
1623 ${when F_NORMAL}
1624 if let y @ Some(_) = $ftype::is_structural_keyword(kw) {
1625 return y;
1626 }
1627 )
1628 None
1629 }
1630 fn from_items<'s>(
1631 input: &mut ItemStream<'s>,
1632 stop_outer: stop_at!(),
1633 ) -> Result<Self, ErrorProblem> {
1634 let stop_inner = stop_outer
1635 $(
1636 ${when F_NORMAL}
1637 | StopAt($ftype::is_intro_item_keyword)
1638 )
1639 ;
1640 Ok(VoteAuthoritySection { $(
1641 ${when F_NORMAL}
1642 $fname: NetdocParseable::from_items(input, stop_inner)?,
1643 )
1644 __non_exhaustive: (),
1645 })
1646 }
1647 }
1648
1649 impl NetdocEncodable for VoteAuthoritySection {
1650 fn encode_unsigned(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
1651 $(
1652 ${when F_NORMAL}
1653 self.$fname.encode_unsigned(out)?;
1654 )
1655 Ok(())
1656 }
1657 }
1658}
1659
1660#[derive(Deftly, Clone, Debug)]
1667#[derive_deftly(VoteAuthoritySection, Constructor)]
1668#[allow(clippy::exhaustive_structs)]
1669pub struct VoteAuthoritySection {
1670 #[deftly(constructor)]
1672 pub authority: VoteAuthorityEntry,
1673
1674 #[deftly(constructor)]
1676 pub cert: EmbeddedCert<AuthCert, EncodedAuthCert>,
1677
1678 #[doc(hidden)]
1679 #[deftly(netdoc(skip))]
1680 pub __non_exhaustive: (),
1681}
1682
1683#[derive(Debug, Clone, Deftly)]
1689#[derive_deftly(Constructor, NetdocEncodableFields, NetdocParseableFields)]
1690#[allow(clippy::exhaustive_structs)]
1691pub struct ConsensusFooterFields {
1692 #[deftly(netdoc(default))]
1696 pub bandwidth_weights: ParamValues<i32>,
1697
1698 #[doc(hidden)]
1699 #[deftly(netdoc(skip))]
1700 pub __non_exhaustive: (),
1701}
1702
1703pub type MdConsensus = md::Consensus;
1706
1707pub type UnvalidatedMdConsensus = md::UnvalidatedConsensus;
1710
1711pub type UncheckedMdConsensus = md::UncheckedConsensus;
1714
1715pub type PlainConsensus = plain::Consensus;
1718
1719pub type UnvalidatedPlainConsensus = plain::UnvalidatedConsensus;
1722
1723pub type UncheckedPlainConsensus = plain::UncheckedConsensus;
1726
1727decl_keyword! {
1728 #[non_exhaustive]
1733 #[allow(missing_docs)]
1734 pub NetstatusKwd {
1735 "network-status-version" => NETWORK_STATUS_VERSION,
1737 "vote-status" => VOTE_STATUS,
1738 "consensus-methods" => CONSENSUS_METHODS,
1739 "consensus-method" => CONSENSUS_METHOD,
1740 "published" => PUBLISHED,
1741 "valid-after" => VALID_AFTER,
1742 "fresh-until" => FRESH_UNTIL,
1743 "valid-until" => VALID_UNTIL,
1744 "voting-delay" => VOTING_DELAY,
1745 "client-versions" => CLIENT_VERSIONS,
1746 "server-versions" => SERVER_VERSIONS,
1747 "known-flags" => KNOWN_FLAGS,
1748 "flag-thresholds" => FLAG_THRESHOLDS,
1749 "recommended-client-protocols" => RECOMMENDED_CLIENT_PROTOCOLS,
1750 "required-client-protocols" => REQUIRED_CLIENT_PROTOCOLS,
1751 "recommended-relay-protocols" => RECOMMENDED_RELAY_PROTOCOLS,
1752 "required-relay-protocols" => REQUIRED_RELAY_PROTOCOLS,
1753 "params" => PARAMS,
1754 "bandwidth-file-headers" => BANDWIDTH_FILE_HEADERS,
1755 "bandwidth-file-digest" => BANDWIDTH_FILE_DIGEST,
1756 "shared-rand-previous-value" => SHARED_RAND_PREVIOUS_VALUE,
1760 "shared-rand-current-value" => SHARED_RAND_CURRENT_VALUE,
1761
1762 "dir-source" => DIR_SOURCE,
1764 "contact" => CONTACT,
1765
1766 "legacy-dir-key" => LEGACY_DIR_KEY,
1768 "shared-rand-participate" => SHARED_RAND_PARTICIPATE,
1769 "shared-rand-commit" => SHARED_RAND_COMMIT,
1770
1771 "vote-digest" => VOTE_DIGEST,
1773
1774 "dir-key-certificate-version" => DIR_KEY_CERTIFICATE_VERSION,
1776
1777 "r" => RS_R,
1779 "a" => RS_A,
1780 "s" => RS_S,
1781 "v" => RS_V,
1782 "pr" => RS_PR,
1783 "w" => RS_W,
1784 "p" => RS_P,
1785 "m" => RS_M,
1786 "id" => RS_ID,
1787
1788 "directory-footer" => DIRECTORY_FOOTER,
1790 "bandwidth-weights" => BANDWIDTH_WEIGHTS,
1791 "directory-signature" => DIRECTORY_SIGNATURE,
1792 }
1793}
1794
1795static NS_HEADER_RULES_COMMON_: LazyLock<SectionRulesBuilder<NetstatusKwd>> = LazyLock::new(|| {
1797 use NetstatusKwd::*;
1798 let mut rules = SectionRules::builder();
1799 rules.add(NETWORK_STATUS_VERSION.rule().required().args(1..=2));
1800 rules.add(VOTE_STATUS.rule().required().args(1..));
1801 rules.add(VALID_AFTER.rule().required());
1802 rules.add(FRESH_UNTIL.rule().required());
1803 rules.add(VALID_UNTIL.rule().required());
1804 rules.add(VOTING_DELAY.rule().args(2..));
1805 rules.add(CLIENT_VERSIONS.rule());
1806 rules.add(SERVER_VERSIONS.rule());
1807 rules.add(KNOWN_FLAGS.rule().required());
1808 rules.add(RECOMMENDED_CLIENT_PROTOCOLS.rule().args(1..));
1809 rules.add(RECOMMENDED_RELAY_PROTOCOLS.rule().args(1..));
1810 rules.add(REQUIRED_CLIENT_PROTOCOLS.rule().args(1..));
1811 rules.add(REQUIRED_RELAY_PROTOCOLS.rule().args(1..));
1812 rules.add(PARAMS.rule());
1813 rules
1814});
1815static NS_HEADER_RULES_CONSENSUS: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1817 use NetstatusKwd::*;
1818 let mut rules = NS_HEADER_RULES_COMMON_.clone();
1819 rules.add(CONSENSUS_METHOD.rule().args(1..=1));
1820 rules.add(SHARED_RAND_PREVIOUS_VALUE.rule().args(2..));
1821 rules.add(SHARED_RAND_CURRENT_VALUE.rule().args(2..));
1822 rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1823 rules.build()
1824});
1825static NS_VOTERINFO_RULES_CONSENSUS: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1856 use NetstatusKwd::*;
1857 let mut rules = SectionRules::builder();
1858 rules.add(DIR_SOURCE.rule().required().args(6..));
1859 rules.add(CONTACT.rule().required());
1860 rules.add(VOTE_DIGEST.rule().required());
1861 rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1862 rules.build()
1863});
1864static NS_ROUTERSTATUS_RULES_COMMON_: LazyLock<SectionRulesBuilder<NetstatusKwd>> =
1866 LazyLock::new(|| {
1867 use NetstatusKwd::*;
1868 let mut rules = SectionRules::builder();
1869 rules.add(RS_A.rule().may_repeat().args(1..));
1870 rules.add(RS_S.rule().required());
1871 rules.add(RS_V.rule());
1872 rules.add(RS_PR.rule().required());
1873 rules.add(RS_W.rule());
1874 rules.add(RS_P.rule().args(2..));
1875 rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1876 rules
1877 });
1878
1879static NS_ROUTERSTATUS_RULES_PLAIN: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1881 use NetstatusKwd::*;
1882 let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
1883 rules.add(RS_R.rule().required().args(8..));
1884 rules.build()
1885});
1886
1887static NS_ROUTERSTATUS_RULES_MDCON: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1900 use NetstatusKwd::*;
1901 let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
1902 rules.add(RS_R.rule().required().args(6..));
1903 rules.add(RS_M.rule().required().args(1..));
1904 rules.build()
1905});
1906static NS_FOOTER_RULES: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1908 use NetstatusKwd::*;
1909 let mut rules = SectionRules::builder();
1910 rules.add(DIRECTORY_FOOTER.rule().required().no_args());
1911 rules.add(BANDWIDTH_WEIGHTS.rule());
1913 rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1914 rules.build()
1915});
1916
1917impl ProtoStatus {
1918 fn from_section(
1920 sec: &Section<'_, NetstatusKwd>,
1921 recommend_token: NetstatusKwd,
1922 required_token: NetstatusKwd,
1923 ) -> crate::Result<ProtoStatus> {
1924 fn parse(t: Option<&Item<'_, NetstatusKwd>>) -> crate::Result<Protocols> {
1926 if let Some(item) = t {
1927 item.args_as_str()
1928 .parse::<Protocols>()
1929 .map_err(|e| EK::BadArgument.at_pos(item.pos()).with_source(e))
1930 } else {
1931 Ok(Protocols::new())
1932 }
1933 }
1934
1935 let recommended = parse(sec.get(recommend_token))?;
1936 let required = parse(sec.get(required_token))?;
1937 Ok(ProtoStatus {
1938 recommended,
1939 required,
1940 __non_exhaustive: (),
1941 })
1942 }
1943
1944 pub fn required_protocols(&self) -> &Protocols {
1951 &self.required
1952 }
1953
1954 pub fn recommended_protocols(&self) -> &Protocols {
1959 &self.recommended
1960 }
1961}
1962
1963impl<T> std::str::FromStr for ParamValues<T>
1964where
1965 T: std::str::FromStr,
1966 T::Err: std::error::Error,
1967{
1968 type Err = Error;
1969 fn from_str(s: &str) -> crate::Result<Self> {
1970 fn parse_pair<U>(p: &str) -> crate::Result<(String, U)>
1972 where
1973 U: std::str::FromStr,
1974 U::Err: std::error::Error,
1975 {
1976 let parts: Vec<_> = p.splitn(2, '=').collect();
1977 if parts.len() != 2 {
1978 return Err(EK::BadArgument
1979 .at_pos(Pos::at(p))
1980 .with_msg("Missing = in key=value list"));
1981 }
1982 let num = parts[1].parse::<U>().map_err(|e| {
1983 EK::BadArgument
1984 .at_pos(Pos::at(parts[1]))
1985 .with_msg(e.to_string())
1986 })?;
1987 Ok((parts[0].to_string(), num))
1988 }
1989
1990 let params = s
1991 .split(' ')
1992 .filter(|p| !p.is_empty())
1993 .map(parse_pair)
1994 .try_collect()?;
1995 Ok(ParamValues { params })
1996 }
1997}
1998
1999impl FromStr for SharedRandVal {
2000 type Err = Error;
2001 fn from_str(s: &str) -> crate::Result<Self> {
2002 let val: B64 = s.parse()?;
2003 let val = SharedRandVal(val.into_array()?);
2004 Ok(val)
2005 }
2006}
2007impl Display for SharedRandVal {
2008 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2009 Display::fmt(&B64::from(Vec::from(self.0)), f)
2010 }
2011}
2012impl NormalItemArgument for SharedRandVal {}
2013
2014impl SharedRandStatus {
2015 fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Self> {
2018 match item.kwd() {
2019 NetstatusKwd::SHARED_RAND_PREVIOUS_VALUE | NetstatusKwd::SHARED_RAND_CURRENT_VALUE => {}
2020 _ => {
2021 return Err(Error::from(internal!(
2022 "wrong keyword {:?} on shared-random value",
2023 item.kwd()
2024 ))
2025 .at_pos(item.pos()));
2026 }
2027 }
2028 let n_reveals: u8 = item.parse_arg(0)?;
2029 let value: SharedRandVal = item.parse_arg(1)?;
2030 let timestamp = item.parse_optional_arg::<Iso8601TimeNoSp>(2)?;
2032 Ok(SharedRandStatus {
2033 n_reveals,
2034 value,
2035 timestamp,
2036 __non_exhaustive: (),
2037 })
2038 }
2039
2040 pub fn value(&self) -> &SharedRandVal {
2042 &self.value
2043 }
2044
2045 pub fn timestamp(&self) -> Option<std::time::SystemTime> {
2047 self.timestamp.map(|t| t.0)
2048 }
2049}
2050
2051impl DirSource {
2052 fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Self> {
2054 if item.kwd() != NetstatusKwd::DIR_SOURCE {
2055 return Err(
2056 Error::from(internal!("Bad keyword {:?} on dir-source", item.kwd()))
2057 .at_pos(item.pos()),
2058 );
2059 }
2060 let nickname = item
2061 .required_arg(0)?
2062 .parse()
2063 .map_err(|e: InvalidNickname| {
2064 EK::BadArgument.at_pos(item.pos()).with_msg(e.to_string())
2065 })?;
2066 let identity = item.parse_arg(1)?;
2067 let hostname = item
2068 .required_arg(2)?
2069 .parse()
2070 .map_err(|e: InvalidInternetHost| {
2071 EK::BadArgument.at_pos(item.pos()).with_msg(e.to_string())
2072 })?;
2073 let ip = item.parse_arg(3)?;
2074 let dir_port = item.parse_arg(4)?;
2075 let or_port = item.parse_arg(5)?;
2076
2077 Ok(DirSource {
2078 nickname,
2079 identity,
2080 hostname,
2081 ip,
2082 dir_port,
2083 or_port,
2084 __non_exhaustive: (),
2085 })
2086 }
2087}
2088
2089impl ConsensusAuthorityEntry {
2090 fn from_section(sec: &Section<'_, NetstatusKwd>) -> crate::Result<ConsensusAuthorityEntry> {
2092 use NetstatusKwd::*;
2093 #[allow(clippy::unwrap_used)]
2096 let first = sec.first_item().unwrap();
2097 if first.kwd() != DIR_SOURCE {
2098 return Err(Error::from(internal!(
2099 "Wrong keyword {:?} at start of voter info",
2100 first.kwd()
2101 ))
2102 .at_pos(first.pos()));
2103 }
2104 let dir_source = DirSource::from_item(sec.required(DIR_SOURCE)?)?;
2105
2106 let contact = sec.required(CONTACT)?;
2107 let contact = contact
2113 .args_as_str()
2114 .parse()
2115 .map_err(|err: InvalidContactInfo| {
2116 EK::BadArgument
2117 .with_msg(err.to_string())
2118 .at_pos(contact.pos())
2119 })?;
2120
2121 let vote_digest = sec.required(VOTE_DIGEST)?.parse_arg::<B16U>(0)?;
2122
2123 Ok(ConsensusAuthorityEntry {
2124 dir_source,
2125 contact,
2126 vote_digest,
2127 __non_exhaustive: (),
2128 })
2129 }
2130}
2131
2132impl RelayBandwidthItem {
2133 pub fn new_no_info() -> Self {
2137 RelayBandwidthItem {
2138 effective: RelayBandwidth::default(),
2139 params: Unknown::new_discard(),
2140 }
2141 }
2142
2143 pub fn from_effective(effective: RelayBandwidth) -> Self {
2145 RelayBandwidthItem {
2146 effective,
2147 params: Unknown::new_discard(),
2148 }
2149 }
2150
2151 pub fn effective(&self) -> RelayBandwidth {
2158 self.effective
2159 }
2160
2161 pub fn params(&self) -> Unknown<&Option<ParamValues<u32>>> {
2169 self.params.as_ref()
2170 }
2171
2172 fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<RelayBandwidthItem> {
2174 if item.kwd() != NetstatusKwd::RS_W {
2175 return Err(
2176 Error::from(internal!("Wrong keyword {:?} on W line", item.kwd()))
2177 .at_pos(item.pos()),
2178 );
2179 }
2180
2181 let params = item.args_as_str().parse()?;
2182 let effective =
2183 RelayBandwidth::from_param_values(¶ms).map_err(|e| e.at_pos(item.pos()))?;
2184
2185 Ok(RelayBandwidthItem {
2186 effective,
2187 params: Unknown::new_discard(),
2188 })
2189 }
2190
2191 const KEYWORD: &str = "w";
2193}
2194
2195#[cfg(feature = "retain-unknown")]
2196impl Default for RelayBandwidthItem {
2197 fn default() -> Self {
2198 RelayBandwidthItem {
2199 effective: RelayBandwidth::default(),
2200 params: Unknown::Retained(None),
2201 }
2202 }
2203}
2204
2205impl RelayBandwidth {
2206 pub fn value(&self) -> u32 {
2208 match *self {
2209 RelayBandwidth::Measured(v) => v,
2210 RelayBandwidth::Unmeasured(v) => v,
2211 }
2212 }
2213
2214 pub fn is_measured(&self) -> bool {
2216 matches!(self, RelayBandwidth::Measured(_))
2217 }
2218
2219 pub fn is_nonzero(&self) -> bool {
2221 self.value() != 0
2222 }
2223
2224 fn from_param_values(params: &ParamValues<u32>) -> crate::Result<RelayBandwidth> {
2228 params
2229 .try_into()
2230 .map_err(|e: InvalidRelayBandwidth| EK::BadArgument.with_msg(e.to_string()))
2231 }
2232}
2233
2234impl Default for RelayBandwidth {
2235 fn default() -> RelayBandwidth {
2236 RelayBandwidth::Unmeasured(0)
2237 }
2238}
2239
2240impl TryFrom<&ParamValues<u32>> for RelayBandwidth {
2241 type Error = InvalidRelayBandwidth;
2242
2243 fn try_from(params: &ParamValues<u32>) -> Result<RelayBandwidth, InvalidRelayBandwidth> {
2244 let bw = params.params.get("Bandwidth");
2245 let unmeas = params.params.get("Unmeasured");
2246
2247 let bw = match bw {
2248 None => return Ok(RelayBandwidth::Unmeasured(0)),
2249 Some(b) => *b,
2250 };
2251
2252 match unmeas {
2253 None | Some(0) => Ok(RelayBandwidth::Measured(bw)),
2254 Some(1) => Ok(RelayBandwidth::Unmeasured(bw)),
2255 _ => Err(InvalidRelayBandwidth::InvalidUnmeasured),
2256 }
2257 }
2258}
2259
2260#[cfg(feature = "retain-unknown")]
2261impl TryFrom<ParamValues<u32>> for RelayBandwidthItem {
2262 type Error = InvalidRelayBandwidth;
2263
2264 fn try_from(params: ParamValues<u32>) -> Result<RelayBandwidthItem, InvalidRelayBandwidth> {
2265 Ok(RelayBandwidthItem {
2266 effective: (¶ms).try_into()?,
2267 params: Unknown::Retained(Some(params)),
2268 })
2269 }
2270}
2271
2272mod parse2_impls {
2276 use super::*;
2277 pub(super) use parse2::{
2278 ArgumentError as AE, ArgumentStream, ErrorProblem as EP, ItemArgumentParseable,
2279 ItemValueParseable, NetdocParseableFields,
2280 };
2281 use std::result::Result;
2282
2283 impl<T: FromStr + NormalItemArgument> ItemValueParseable for ParamValues<T>
2285 where
2286 T::Err: std::error::Error,
2287 {
2288 fn from_unparsed(item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
2289 item.check_no_object()?;
2290 item.args_copy()
2291 .into_remaining()
2292 .parse()
2293 .map_err(item.invalid_argument_handler("parameters"))
2294 }
2295 }
2296
2297 impl ItemValueParseable for NetParams {
2298 fn from_unparsed(item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
2299 let params = ParamValues::from_unparsed(item)?;
2300 Ok(NetParams { params })
2301 }
2302 }
2303
2304 impl NetdocParseableFields for RelayBandwidthItem {
2305 type Accumulator = Option<ParamValues<u32>>;
2306
2307 fn is_item_keyword(kw: KeywordRef) -> bool {
2308 kw == Self::KEYWORD
2309 }
2310
2311 fn accumulate_item(acc: &mut Self::Accumulator, item: UnparsedItem) -> Result<(), EP> {
2312 if acc.is_some() {
2313 return Err(EP::ItemRepeated);
2314 }
2315 item.check_no_object()?;
2316 let params = ParamValues::from_unparsed(item)?;
2317 *acc = Some(params);
2318 Ok(())
2319 }
2320
2321 fn finish(params: Self::Accumulator, items: &ItemStream) -> Result<Self, EP> {
2322 let effective = params
2323 .as_ref()
2324 .map(TryFrom::try_from)
2325 .transpose()
2326 .map_err(|_| EP::OtherBadDocument("invalid information in `w` item"))?
2327 .unwrap_or_default();
2328
2329 let params = items.parse_options().retain_unknown_values.map(|()| params);
2330
2331 Ok(RelayBandwidthItem { effective, params })
2332 }
2333 }
2334
2335 impl ItemValueParseable for rs::SoftwareVersion {
2336 fn from_unparsed(mut item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
2337 item.check_no_object()?;
2338 item.args_mut()
2339 .into_remaining()
2340 .parse()
2341 .map_err(item.invalid_argument_handler("version"))
2342 }
2343 }
2344
2345 impl ItemArgumentParseable for IgnoredPublicationTimeSp {
2346 fn from_args(a: &mut ArgumentStream) -> Result<IgnoredPublicationTimeSp, AE> {
2347 let mut next_arg = || a.next().ok_or(AE::Missing);
2348 let _: &str = next_arg()?;
2349 let _: &str = next_arg()?;
2350 Ok(IgnoredPublicationTimeSp)
2351 }
2352 }
2353}
2354
2355mod encode_impls {
2359 use super::*;
2360 use std::result::Result;
2361 pub(crate) use {
2362 crate::encode::{ItemEncoder, ItemValueEncodable, NetdocEncodableFields},
2363 tor_error::Bug,
2364 };
2365
2366 impl NetdocEncodableFields for RelayBandwidthItem {
2367 fn encode_fields(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
2368 if let Some(w) = self.params.as_ref().into_retained()? {
2369 w.write_item_value_onto(out.item(Self::KEYWORD))?;
2370 }
2371 Ok(())
2372 }
2373 }
2374
2375 impl<T: NormalItemArgument + Ord + Display> ItemValueEncodable for ParamValues<T> {
2377 fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
2378 for (k, v) in self.iter().collect::<BTreeSet<_>>() {
2379 if k.is_empty()
2380 || k.chars()
2381 .any(|c| c.is_whitespace() || c.is_control() || c == '=')
2382 {
2383 return Err(bad_api_usage!(
2385 "tried to encode NetParms with unreasonable keyword {k:?}"
2386 ));
2387 }
2388 out.args_raw_string(&format_args!("{k}={v}"));
2389 }
2390 Ok(())
2391 }
2392 }
2393
2394 impl ItemValueEncodable for NetParams {
2396 fn write_item_value_onto(&self, out: ItemEncoder) -> Result<(), Bug> {
2397 self.params.write_item_value_onto(out)
2398 }
2399 }
2400
2401 impl ItemValueEncodable for rs::SoftwareVersion {
2402 fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
2403 out.args_raw_string(self);
2404 Ok(())
2405 }
2406 }
2407
2408 impl ItemArgument for IgnoredPublicationTimeSp {
2409 fn write_arg_onto(&self, out: &mut ItemEncoder) -> Result<(), Bug> {
2410 out.args_raw_string(&"2000-01-01 00:00:01");
2411 Ok(())
2412 }
2413 }
2414}
2415
2416impl ConsensusFooterFields {
2417 fn from_section(sec: &Section<'_, NetstatusKwd>) -> crate::Result<ConsensusFooterFields> {
2419 use NetstatusKwd::*;
2420 sec.required(DIRECTORY_FOOTER)?;
2421
2422 let bandwidth_weights = sec
2423 .maybe(BANDWIDTH_WEIGHTS)
2424 .args_as_str()
2425 .unwrap_or("")
2426 .parse()?;
2427
2428 Ok(ConsensusFooterFields {
2429 bandwidth_weights,
2430 __non_exhaustive: (),
2431 })
2432 }
2433}
2434
2435mod proto_statuses_parse2_encode {
2439 use super::encode_impls::*;
2440 use super::parse2_impls::*;
2441 use super::*;
2442 use paste::paste;
2443 use std::result::Result;
2444
2445 macro_rules! impl_proto_statuses { { $( $rr:ident $cr:ident; )* } => { paste! {
2459 #[derive(Deftly)]
2460 #[derive_deftly(NetdocParseableFields)]
2461 #[allow(unreachable_pub)]
2463 pub struct ProtoStatusesParseHelper {
2464 $(
2465 #[deftly(netdoc(default))]
2466 [<$rr _ $cr _protocols>]: Protocols,
2467 )*
2468 }
2469
2470 pub use ProtoStatusesParseHelperNetdocParseAccumulator
2472 as ProtoStatusesNetdocParseAccumulator;
2473
2474 impl NetdocParseableFields for ProtoStatuses {
2475 type Accumulator = ProtoStatusesNetdocParseAccumulator;
2476 fn is_item_keyword(kw: KeywordRef<'_>) -> bool {
2477 ProtoStatusesParseHelper::is_item_keyword(kw)
2478 }
2479 fn accumulate_item(
2480 acc: &mut Self::Accumulator,
2481 item: UnparsedItem<'_>,
2482 ) -> Result<(), EP> {
2483 ProtoStatusesParseHelper::accumulate_item(acc, item)
2484 }
2485 fn finish(acc: Self::Accumulator, items: &ItemStream<'_>) -> Result<Self, EP> {
2486 let parse = ProtoStatusesParseHelper::finish(acc, items)?;
2487 let mut out = ProtoStatuses::default();
2488 $(
2489 out.$cr.$rr = parse.[< $rr _ $cr _protocols >];
2490 )*
2491 Ok(out)
2492 }
2493 }
2494
2495 impl NetdocEncodableFields for ProtoStatuses {
2496 fn encode_fields(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
2497 $(
2498 self.$cr.$rr.write_item_value_onto(
2499 out.item(concat!(stringify!($rr), "-", stringify!($cr), "-protocols"))
2500 )?;
2501 )*
2502 Ok(())
2503 }
2504 }
2505 } } }
2506
2507 impl_proto_statuses! {
2508 recommended client;
2509 recommended relay;
2510 required client;
2511 required relay;
2512 }
2513}
2514
2515impl Signature {
2516 fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Signature> {
2518 if item.kwd() != NetstatusKwd::DIRECTORY_SIGNATURE {
2519 return Err(Error::from(internal!(
2520 "Wrong keyword {:?} for directory signature",
2521 item.kwd()
2522 ))
2523 .at_pos(item.pos()));
2524 }
2525
2526 let (digest_algo, id_fp, sk_fp) = if item.n_args() > 2 {
2527 (
2528 item.required_arg(0)?,
2529 item.required_arg(1)?,
2530 item.required_arg(2)?,
2531 )
2532 } else {
2533 ("sha1", item.required_arg(0)?, item.required_arg(1)?)
2535 };
2536
2537 let digest_algo = digest_algo.to_string().parse().void_unwrap();
2538 let digest_algo = DigestAlgoInSignature(Some(digest_algo));
2539 let id_fingerprint = id_fp.parse::<Fingerprint>()?.into();
2540 let sk_fingerprint = sk_fp.parse::<Fingerprint>()?.into();
2541 let key_ids = AuthCertKeyIds {
2542 id_fingerprint,
2543 sk_fingerprint,
2544 };
2545 let signature = item.obj("SIGNATURE")?;
2546
2547 Ok(Signature {
2548 digest_algo,
2549 key_ids,
2550 signature,
2551 __non_exhaustive: (),
2552 })
2553 }
2554
2555 fn matches_cert(&self, cert: &AuthCert) -> bool {
2558 cert.key_ids() == self.key_ids
2559 }
2560
2561 fn find_cert<'a>(&self, certs: &'a [AuthCert]) -> Option<&'a AuthCert> {
2564 certs.iter().find(|&c| self.matches_cert(c))
2565 }
2566
2567 fn signature_to_verify<'r>(
2571 &'r self,
2572 signed_digest: &'r [u8],
2573 certs: &'r [AuthCert],
2574 ) -> Option<ConsensusSignatureToVerify> {
2575 let cert = self.find_cert(certs)?;
2576 let key = cert.signing_key();
2577 Some(ConsensusSignatureToVerify {
2578 key,
2579 signed_digest,
2580 signature: &self.signature,
2581 })
2582 }
2583}
2584
2585impl EncodeOrd for Signature {
2586 fn encode_cmp(&self, other: &Self) -> std::cmp::Ordering {
2587 let k: for<'s> fn(&'_ Signature) -> (&'_ _, &'_ _) = |s| (&s.key_ids, &s.signature);
2588 Ord::cmp(&k(self), &k(other))
2589 }
2590}
2591
2592#[derive(Debug, Clone, Copy)]
2598struct ConsensusSignatureToVerify<'r> {
2599 key: &'r ll::pk::rsa::PublicKey,
2601
2602 signed_digest: &'r [u8],
2604
2605 signature: &'r [u8],
2607}
2608
2609pub(crate) struct SignatureVerifiedIfIntended {}
2618
2619impl<'r> ConsensusSignatureToVerify<'r> {
2620 fn verify(self) -> Result<SignatureVerifiedIfIntended, VerifyFailed> {
2623 self.key.verify(self.signed_digest, self.signature)?;
2624 Ok(SignatureVerifiedIfIntended {})
2625 }
2626}
2627
2628#[derive(Debug, Clone, Copy)]
2632pub(crate) enum VerifyGeneralTrustedAuthorities<'r> {
2633 TrustThese {
2635 trusted: &'r [RsaIdentity],
2637 },
2638
2639 AnyOneOfThese {
2641 trusted: &'r [RsaIdentity],
2643 },
2644
2645 HazardouslyAssumeAllAuthCertsAreReal {
2650 n_authorities: usize,
2654 },
2655}
2656
2657pub fn consensus_threshold(n_authorities: usize) -> std::ops::RangeFrom<usize> {
2687 (n_authorities / 2) + 1 ..
2689}
2690
2691impl SignatureGroup {
2692 fn list_missing(&self, certs: &[AuthCert]) -> (usize, Vec<&Signature>) {
2699 let mut ok: HashSet<RsaIdentity> = HashSet::new();
2700 let mut missing = Vec::new();
2701 for sig in &self.signatures {
2702 let id_fingerprint = &sig.key_ids.id_fingerprint;
2703 if ok.contains(id_fingerprint) {
2704 continue;
2705 }
2706 if sig.find_cert(certs).is_some() {
2707 ok.insert(*id_fingerprint);
2708 continue;
2709 }
2710
2711 missing.push(sig);
2712 }
2713 (ok.len(), missing)
2714 }
2715
2716 fn could_validate(&self, authorities: &[&RsaIdentity]) -> bool {
2720 let mut signed_by: HashSet<RsaIdentity> = HashSet::new();
2721 for sig in &self.signatures {
2722 let id_fp = &sig.key_ids.id_fingerprint;
2723 if signed_by.contains(id_fp) {
2724 continue;
2726 }
2727 if authorities.contains(&id_fp) {
2728 signed_by.insert(*id_fp);
2729 }
2730 }
2731
2732 consensus_threshold(authorities.len()).contains(&signed_by.len())
2733 }
2734
2735 fn validate(&self, n_authorities: usize, certs: &[AuthCert]) -> Result<(), VerifyFailed> {
2742 self.verify_general(
2745 VerifyGeneralTrustedAuthorities::HazardouslyAssumeAllAuthCertsAreReal { n_authorities },
2746 certs,
2747 |tv| tv.verify(),
2748 )
2749 }
2750
2751 fn verify_general<E>(
2780 &self,
2781 trusted_authorities: VerifyGeneralTrustedAuthorities,
2782 certs: &[AuthCert],
2783 do_verify: impl Fn(ConsensusSignatureToVerify) -> Result<SignatureVerifiedIfIntended, E>,
2784 ) -> Result<(), E>
2785 where
2786 ConsensusVerifiabilityError: Into<E>,
2787 {
2788 use VerifyGeneralTrustedAuthorities as TA;
2789
2790 let mut ok: HashSet<RsaIdentity> = HashSet::new();
2794 let mut missing = HashSet::new();
2795 let mut verify_failed = Ok(());
2796
2797 for sig in &self.signatures {
2798 let Signature {
2800 digest_algo,
2801 key_ids:
2802 AuthCertKeyIds {
2803 id_fingerprint,
2804 sk_fingerprint: _,
2807 },
2808 signature: _,
2810 __non_exhaustive: (),
2811 } = sig;
2812
2813 match trusted_authorities {
2814 TA::TrustThese { trusted } | TA::AnyOneOfThese { trusted } => {
2815 if !trusted.contains(id_fingerprint) {
2816 continue;
2817 }
2818 }
2819 TA::HazardouslyAssumeAllAuthCertsAreReal { .. } => {
2820 }
2822 }
2823
2824 if ok.contains(id_fingerprint) {
2825 continue;
2828 }
2829
2830 let Some(d) = self.hashes.hash_slice(digest_algo) else {
2831 continue;
2834 };
2835
2836 let Some(tv) = sig.signature_to_verify(d, certs) else {
2837 missing.insert(sig.key_ids);
2838 continue;
2839 };
2840 match do_verify(tv) {
2841 Ok::<SignatureVerifiedIfIntended, _>(_) => {
2842 ok.insert(*id_fingerprint);
2843 }
2844 Err(e) => {
2845 verify_failed = Err(e);
2846 }
2847 }
2848 }
2849
2850 let n_authorities = match trusted_authorities {
2851 TA::TrustThese { trusted } => trusted.len(),
2852 TA::HazardouslyAssumeAllAuthCertsAreReal { n_authorities: n } => n,
2853 TA::AnyOneOfThese { .. } => {
2854 1
2858 }
2859 };
2860 let threshold = consensus_threshold(n_authorities);
2861
2862 if threshold.contains(&ok.len()) {
2863 Ok(())
2864 } else {
2865 verify_failed?;
2867
2868 Err(if missing.is_empty() {
2870 ConsensusVerifiabilityError::InsufficientTrustedSigners
2871 } else {
2872 let deficit = threshold.start - ok.len();
2873 ConsensusVerifiabilityError::MissingAuthCerts { missing, deficit }
2874 }
2875 .into())
2876 }
2877 }
2878}
2879
2880impl From<ConsensusVerifiabilityError> for VerifyFailed {
2881 fn from(cve: ConsensusVerifiabilityError) -> VerifyFailed {
2882 use ConsensusVerifiabilityError as CVE;
2883 use VerifyFailed as VF;
2884 match cve {
2885 CVE::InsufficientTrustedSigners => VF::InsufficientTrustedSigners,
2886 CVE::MissingAuthCerts { .. } => VF::InsufficientTrustedSigners,
2887 }
2888 }
2889}
2890
2891impl From<ConsensusVerifyFailed> for VerifyFailed {
2892 fn from(cvf: ConsensusVerifyFailed) -> VerifyFailed {
2893 use ConsensusVerifyFailed as CVF;
2894 use VerifyFailed as VF;
2895 match cvf {
2896 CVF::CertificationInsufficient { .. } => VF::InsufficientTrustedSigners,
2897 CVF::InvalidSignature { .. } => VF::VerifyFailed,
2898 }
2899 }
2900}
2901
2902#[cfg(test)]
2903mod test {
2904 #![allow(clippy::bool_assert_comparison)]
2906 #![allow(clippy::clone_on_copy)]
2907 #![allow(clippy::dbg_macro)]
2908 #![allow(clippy::mixed_attributes_style)]
2909 #![allow(clippy::print_stderr)]
2910 #![allow(clippy::print_stdout)]
2911 #![allow(clippy::single_char_pattern)]
2912 #![allow(clippy::unwrap_used)]
2913 #![allow(clippy::unchecked_time_subtraction)]
2914 #![allow(clippy::useless_vec)]
2915 #![allow(clippy::needless_pass_by_value)]
2916 #![allow(clippy::string_slice)] use super::*;
2919 use crate::doc::authcert::AuthCertUnverified;
2920 use crate::encode::{NetdocEncodable, NetdocEncodableFields};
2921 use crate::parse2::{ParseInput, parse_netdoc, parse_netdoc_multiple};
2922 use crate::test_support::{raw_find_item_rhs, regsub};
2923 use anyhow::Context as _;
2924 use assert_matches::assert_matches;
2925 use hex_literal::hex;
2926 use humantime::parse_rfc3339;
2927 use std::fmt::Debug;
2928 use std::fs;
2929 use std::time::Duration;
2930 use tor_checkable::TimeBound;
2931
2932 const CERTS: &str = include_str!("../../testdata/authcerts2.txt");
2933 const CONSENSUS: &str = include_str!("../../testdata/mdconsensus1.txt");
2934
2935 const PLAIN_CERTS: &str = include_str!("../../testdata2/cached-certs");
2936 const PLAIN_CONSENSUS: &str = include_str!("../../testdata2/cached-consensus");
2937
2938 fn read_bad(fname: &str) -> String {
2939 use std::fs;
2940 use std::path::PathBuf;
2941 let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
2942 path.push("testdata");
2943 path.push("bad-mdconsensus");
2944 path.push(fname);
2945
2946 fs::read_to_string(path).unwrap()
2947 }
2948
2949 #[test]
2950 fn parse_and_validate_md() -> crate::Result<()> {
2951 use std::net::SocketAddr;
2952 use tor_checkable::{SelfSigned, TimeBound};
2953 let mut certs = Vec::new();
2954 for cert in AuthCert::parse_multiple(CERTS)? {
2955 let cert = cert?.check_signature()?.dangerously_assume_timely();
2956 certs.push(cert);
2957 }
2958 let auth_ids: Vec<_> = certs.iter().map(|c| c.id_fingerprint()).collect();
2959
2960 assert_eq!(certs.len(), 3);
2961
2962 let (_, _, consensus) = MdConsensus::parse(CONSENSUS)?;
2963 let consensus = consensus.dangerously_assume_timely().set_n_authorities(3);
2964
2965 assert!(consensus.authorities_are_correct(&auth_ids));
2967 assert!(consensus.authorities_are_correct(&auth_ids[0..1]));
2969 {
2970 let bad_auth_id = (*b"xxxxxxxxxxxxxxxxxxxx").into();
2973 assert!(!consensus.authorities_are_correct(&[&bad_auth_id]));
2974 }
2975
2976 let missing = consensus.key_is_correct(&[]).err().unwrap();
2977 assert_eq!(3, missing.len());
2978 assert!(consensus.key_is_correct(&certs).is_ok());
2979 let missing = consensus.key_is_correct(&certs[0..1]).err().unwrap();
2980 assert_eq!(2, missing.len());
2981
2982 let same_three_times = vec![certs[0].clone(), certs[0].clone(), certs[0].clone()];
2984 let missing = consensus.key_is_correct(&same_three_times).err().unwrap();
2985
2986 assert_eq!(2, missing.len());
2987 assert!(consensus.is_well_signed(&same_three_times).is_err());
2988
2989 assert!(consensus.key_is_correct(&certs).is_ok());
2990 let consensus = consensus.check_signature(&certs)?;
2991
2992 assert_eq!(6, consensus.relays().len());
2993 let r0 = &consensus.relays()[0];
2994 assert_eq!(
2995 r0.md_digest(),
2996 &hex!("73dabe0a0468f4f7a67810a18d11e36731bb1d2ec3634db459100609f3b3f535")
2997 );
2998 assert_eq!(
2999 r0.rsa_identity().as_bytes(),
3000 &hex!("0a3057af2910415794d8ea430309d9ac5f5d524b")
3001 );
3002 assert!(!r0.bandwidth().is_measured());
3003 assert!(!r0.bandwidth().is_nonzero());
3004 let pv = &r0.protovers();
3005 assert!(pv.supports_subver("HSDir", 2));
3006 assert!(!pv.supports_subver("HSDir", 3));
3007 let ip4 = "127.0.0.1:5002".parse::<SocketAddr>().unwrap();
3008 let ip6 = "[::1]:5002".parse::<SocketAddr>().unwrap();
3009 assert!(r0.addrs().any(|a| a == ip4));
3010 assert!(r0.addrs().any(|a| a == ip6));
3011
3012 Ok(())
3013 }
3014
3015 #[test]
3016 fn parse_and_validate_ns() -> crate::Result<()> {
3017 use tor_checkable::{SelfSigned, TimeBound};
3018 let mut certs = Vec::new();
3019 for cert in AuthCert::parse_multiple(PLAIN_CERTS)? {
3020 let cert = cert?.check_signature()?.dangerously_assume_timely();
3021 certs.push(cert);
3022 }
3023 let auth_ids: Vec<_> = certs.iter().map(|c| c.id_fingerprint()).collect();
3024 assert_eq!(certs.len(), 4);
3025
3026 let (_, _, consensus) = PlainConsensus::parse(PLAIN_CONSENSUS)?;
3027 let consensus = consensus.dangerously_assume_timely().set_n_authorities(3);
3028 assert!(consensus.authorities_are_correct(&auth_ids));
3030 assert!(consensus.authorities_are_correct(&auth_ids[0..1]));
3032
3033 assert!(consensus.key_is_correct(&certs).is_ok());
3034
3035 let _consensus = consensus.check_signature(&certs)?;
3036
3037 Ok(())
3038 }
3039
3040 #[test]
3041 fn test_bad() {
3042 use crate::Pos;
3043 fn check(fname: &str, e: &Error) {
3044 let content = read_bad(fname);
3045 let res = MdConsensus::parse(&content);
3046 assert!(res.is_err());
3047 assert_eq!(&res.err().unwrap(), e);
3048 }
3049
3050 check(
3051 "bad-flags",
3052 &EK::BadArgument
3053 .at_pos(Pos::from_line(27, 1))
3054 .with_msg("Flags out of order"),
3055 );
3056 check(
3057 "bad-md-digest",
3058 &EK::BadArgument
3059 .at_pos(Pos::from_line(40, 3))
3060 .with_msg("Invalid base64"),
3061 );
3062 check(
3063 "bad-weight",
3064 &EK::BadArgument
3065 .at_pos(Pos::from_line(67, 141))
3066 .with_msg("invalid digit found in string"),
3067 );
3068 check(
3069 "bad-weights",
3070 &EK::BadArgument
3071 .at_pos(Pos::from_line(51, 13))
3072 .with_msg("invalid digit found in string"),
3073 );
3074 check(
3075 "wrong-order",
3076 &EK::WrongSortOrder.at_pos(Pos::from_line(52, 1)),
3077 );
3078 check(
3079 "wrong-start",
3080 &EK::UnexpectedToken
3081 .with_msg("vote-status")
3082 .at_pos(Pos::from_line(1, 1)),
3083 );
3084 check("wrong-version", &EK::BadDocumentVersion.with_msg("10"));
3085 }
3086
3087 fn gettok(s: &str) -> crate::Result<Item<'_, NetstatusKwd>> {
3088 let mut reader = NetDocReader::new(s)?;
3089 let tok = reader.next().unwrap();
3090 assert!(reader.next().is_none());
3091 tok
3092 }
3093
3094 #[test]
3095 fn test_weight() {
3096 let w = gettok("w Unmeasured=1 Bandwidth=6\n").unwrap();
3097 let w = RelayBandwidthItem::from_item(&w).unwrap();
3098 assert!(!w.effective.is_measured());
3099 assert!(w.effective.is_nonzero());
3100
3101 let w = gettok("w Bandwidth=10\n").unwrap();
3102 let w = RelayBandwidthItem::from_item(&w).unwrap();
3103 assert!(w.effective.is_measured());
3104 assert!(w.effective.is_nonzero());
3105
3106 let w = RelayBandwidthItem::new_no_info();
3107 assert!(!w.effective.is_measured());
3108 assert!(!w.effective.is_nonzero());
3109
3110 let w = gettok("w Mustelid=66 Cheato=7 Unmeasured=1\n").unwrap();
3111 let w = RelayBandwidthItem::from_item(&w).unwrap();
3112 assert!(!w.effective.is_measured());
3113 assert!(!w.effective.is_nonzero());
3114
3115 let w = gettok("r foo\n").unwrap();
3116 let w = RelayBandwidthItem::from_item(&w);
3117 assert!(w.is_err());
3118
3119 let w = gettok("r Bandwidth=6 Unmeasured=Frog\n").unwrap();
3120 let w = RelayBandwidthItem::from_item(&w);
3121 assert!(w.is_err());
3122
3123 let w = gettok("r Bandwidth=6 Unmeasured=3\n").unwrap();
3124 let w = RelayBandwidthItem::from_item(&w);
3125 assert!(w.is_err());
3126 }
3127
3128 #[test]
3129 fn test_netparam() {
3130 let p = "Hello=600 Goodbye=5 Fred=7"
3131 .parse::<ParamValues<u32>>()
3132 .unwrap();
3133 assert_eq!(p.get("Hello"), Some(&600_u32));
3134
3135 let p = "Hello=Goodbye=5 Fred=7".parse::<ParamValues<u32>>();
3136 assert!(p.is_err());
3137
3138 let p = "Hello=Goodbye Fred=7".parse::<ParamValues<u32>>();
3139 assert!(p.is_err());
3140
3141 for bad_kw in ["What=The", "", "\n", "\0"] {
3142 let p = [(bad_kw, 42)].into_iter().collect::<ParamValues<i32>>();
3143 let mut d = NetdocEncoder::new();
3144 let d = (|| {
3145 let i = d.item("bad-psrams");
3146 p.write_item_value_onto(i)?;
3147 d.finish()
3148 })();
3149 let _: tor_error::Bug = d.expect_err(bad_kw);
3150 }
3151 }
3152
3153 #[test]
3154 fn test_sharedrand() {
3155 let sr =
3156 gettok("shared-rand-previous-value 9 5LodY4yWxFhTKtxpV9wAgNA9N8flhUCH0NqQv1/05y4\n")
3157 .unwrap();
3158 let sr = SharedRandStatus::from_item(&sr).unwrap();
3159
3160 assert_eq!(sr.n_reveals, 9);
3161 assert_eq!(
3162 sr.value.0,
3163 hex!("e4ba1d638c96c458532adc6957dc0080d03d37c7e5854087d0da90bf5ff4e72e")
3164 );
3165 assert!(sr.timestamp.is_none());
3166
3167 let sr2 = gettok(
3168 "shared-rand-current-value 9 \
3169 5LodY4yWxFhTKtxpV9wAgNA9N8flhUCH0NqQv1/05y4 2022-01-20T12:34:56\n",
3170 )
3171 .unwrap();
3172 let sr2 = SharedRandStatus::from_item(&sr2).unwrap();
3173 assert_eq!(sr2.n_reveals, sr.n_reveals);
3174 assert_eq!(sr2.value.0, sr.value.0);
3175 assert_eq!(
3176 sr2.timestamp.unwrap().0,
3177 humantime::parse_rfc3339("2022-01-20T12:34:56Z").unwrap()
3178 );
3179
3180 let sr = gettok("foo bar\n").unwrap();
3181 let sr = SharedRandStatus::from_item(&sr);
3182 assert!(sr.is_err());
3183 }
3184
3185 #[test]
3186 fn test_protostatus() {
3187 let my_protocols: Protocols = "Link=7 Cons=1-5 Desc=3-10".parse().unwrap();
3188
3189 let outcome = ProtoStatus {
3190 recommended: "Link=7".parse().unwrap(),
3191 required: "Desc=5".parse().unwrap(),
3192 __non_exhaustive: (),
3193 }
3194 .check_protocols(&my_protocols);
3195 assert!(outcome.is_ok());
3196
3197 let outcome = ProtoStatus {
3198 recommended: "Microdesc=4 Link=7".parse().unwrap(),
3199 required: "Desc=5".parse().unwrap(),
3200 __non_exhaustive: (),
3201 }
3202 .check_protocols(&my_protocols);
3203 assert_eq!(
3204 outcome,
3205 Err(ProtocolSupportError::MissingRecommended(
3206 "Microdesc=4".parse().unwrap()
3207 ))
3208 );
3209
3210 let outcome = ProtoStatus {
3211 recommended: "Microdesc=4 Link=7".parse().unwrap(),
3212 required: "Desc=5 Cons=5-12 Wombat=15".parse().unwrap(),
3213 __non_exhaustive: (),
3214 }
3215 .check_protocols(&my_protocols);
3216 assert_eq!(
3217 outcome,
3218 Err(ProtocolSupportError::MissingRequired(
3219 "Cons=6-12 Wombat=15".parse().unwrap()
3220 ))
3221 );
3222 }
3223
3224 #[test]
3225 fn serialize_protostatus() {
3226 let ps = ProtoStatuses {
3227 client: ProtoStatus {
3228 recommended: "Link=1-5 LinkAuth=2-5".parse().unwrap(),
3229 required: "Link=5 LinkAuth=3".parse().unwrap(),
3230 __non_exhaustive: (),
3231 },
3232 relay: ProtoStatus {
3233 recommended: "Wombat=20-30 Knish=20-30".parse().unwrap(),
3234 required: "Wombat=20-22 Knish=25-27".parse().unwrap(),
3235 __non_exhaustive: (),
3236 },
3237 __non_exhaustive: (),
3238 };
3239 let json = serde_json::to_string(&ps).unwrap();
3240 let ps2 = serde_json::from_str(json.as_str()).unwrap();
3241 assert_eq!(ps, ps2);
3242
3243 let ps3: ProtoStatuses = serde_json::from_str(
3244 r#"{
3245 "client":{
3246 "required":"Link=5 LinkAuth=3",
3247 "recommended":"Link=1-5 LinkAuth=2-5"
3248 },
3249 "relay":{
3250 "required":"Wombat=20-22 Knish=25-27",
3251 "recommended":"Wombat=20-30 Knish=20-30"
3252 }
3253 }"#,
3254 )
3255 .unwrap();
3256 assert_eq!(ps, ps3);
3257 }
3258
3259 #[test]
3261 fn verify_error_netstatus_vote() -> Result<(), anyhow::Error> {
3262 use VerifyFailed as VF;
3263 use VoteVerifyFailed as VVF;
3264 use vote::NetworkStatusUnverified as UV;
3265
3266 let file = "testdata2/v3-status-votes--1";
3267 let text = fs::read_to_string(file).with_context(|| file.to_owned())?;
3268 let input = ParseInput::new(&text, file);
3269 let doc: UV = parse_netdoc(&input)?;
3270 let trusted = || VoteVerifier::new([doc.peek_alleged_authority()]);
3271
3272 let edit_body = |f: &dyn Fn(&mut _)| {
3273 let (mut body, sigs) = doc.clone().unwrap_unverified();
3274 f(&mut body);
3275 UV::from_parts(body, sigs)
3276 };
3277
3278 {
3280 let mut doc = doc.clone();
3281 doc.sigs.sigs.directory_signature.signature.fill(0xff);
3282 assert_matches!(
3283 doc.verify(&mut trusted()),
3284 Err(VVF::InvalidSignature(VF::VerifyFailed))
3285 );
3286 }
3287
3288 {
3290 let doc = doc.clone();
3291 assert_matches!(
3292 doc.verify(&mut VoteVerifier::new([[0x55; _].into()])),
3293 Err(VVF::InvalidSignature(VF::InsufficientTrustedSigners))
3294 );
3295 }
3296
3297 {
3299 let doc = edit_body(&|body| {
3300 body.authority.authority.dir_source.identity.0 = [0x55; _].into();
3301 });
3302 assert_matches!(
3303 doc.verify(&mut trusted()),
3305 Err(VVF::AuthCertWrongAuthority)
3306 );
3307 }
3308
3309 let with_mutated_lifetime = |f: &dyn Fn(&mut Lifetime)| {
3311 let doc = edit_body(&|body| f(&mut body.preamble.lifetime));
3312 assert_matches!(
3313 doc.verify(&mut trusted()),
3315 Err(VVF::AuthCertWrongValidity(_))
3316 );
3317 };
3318 let t_past = parse_rfc3339("1990-01-01T00:02:25Z")?;
3319 let t_future = parse_rfc3339("2010-01-01T00:02:25Z")?;
3320 with_mutated_lifetime(&|lifetime| lifetime.valid_after.0 = t_future);
3321 with_mutated_lifetime(&|lifetime| lifetime.fresh_until.0 = t_past);
3322 with_mutated_lifetime(&|lifetime| lifetime.valid_until.0 = t_past);
3323
3324 {
3326 let mut text = text.clone();
3327 regsub(&mut text, "^dir-key-expires ", "dir-key-expires-SABOTAGED ");
3328 let input = ParseInput::new(&text, file);
3329 let doc: UV = parse_netdoc(&input)?;
3330 assert_matches!(
3331 doc.verify(&mut trusted()),
3333 Err(VVF::AuthCertParseError(..))
3334 );
3335 }
3336
3337 {
3339 let mut trusted = trusted();
3340 assert_matches!(
3341 doc.clone().verify(&mut trusted),
3343 Ok(_)
3344 );
3345 assert_matches!(
3346 doc.clone().verify(&mut trusted),
3347 Err(VVF::DuplicateAuthority(_))
3348 );
3349 }
3350
3351 Ok(())
3352 }
3353
3354 #[cfg(feature = "retain-unknown")]
3355 #[allow(clippy::type_complexity)]
3356 pub(super) fn prep_netstatus_verify<UV: NetdocParseable>(
3357 file: &str,
3358 ) -> anyhow::Result<(UV, String, Vec<AuthCert>, Vec<RsaIdentity>, SystemTime)> {
3359 let text = fs::read_to_string(file).with_context(|| file.to_owned())?;
3360
3361 let now = *raw_find_item_rhs(
3362 include_str!("../../testdata2/cached-microdesc-consensus"),
3363 "valid-after",
3364 )
3365 .parse::<Iso8601TimeSp>()
3366 .unwrap()
3367 + Duration::from_secs(1);
3368
3369 let input = ParseInput::new(&text, file).retain_unknown_values();
3370 let doc: UV = parse_netdoc(&input)?;
3371
3372 let certs = {
3373 let file = "testdata2/cached-certs";
3374 let text = fs::read_to_string(file)?;
3375 let input = ParseInput::new(&text, file);
3376 let certs: Vec<AuthCertUnverified> = parse_netdoc_multiple(&input)?;
3377 certs
3378 .into_iter()
3379 .map(|cert| cert.verify_selfcert(now))
3380 .collect::<Result<Vec<AuthCert>, _>>()?
3381 };
3382
3383 let authorities = certs.iter().map(|cert| *cert.fingerprint).collect_vec();
3384
3385 Ok((doc, text, certs, authorities, now))
3386 }
3387
3388 #[cfg(feature = "retain-unknown")]
3401 fn roundtrip_netstatus<UV, V, VE>(
3402 file: &str,
3405 verify: impl FnOnce(UV, &[RsaIdentity], &[AuthCert]) -> Result<TimeRangeBound<V>, VE>,
3406 adjust_now: Duration,
3407 ) -> anyhow::Result<()>
3408 where
3409 UV: NetdocParseable + NetdocParseableUnverified + MungeForRoundtrip,
3410 UV::Signatures: Clone + Debug + NetdocEncodableFields,
3411 VE: Debug + std::error::Error + Send + Sync + 'static,
3412 V: Debug + NetdocEncodable,
3413 {
3414 let (doc, text, certs, authorities, now) = prep_netstatus_verify::<UV>(file)?;
3415
3416 let now = now + adjust_now;
3417
3418 let sigs = doc.inspect_unverified().1.sigs.clone();
3419
3420 let doc = verify(doc, &authorities, &certs)?.if_valid_at(&now)?;
3421
3422 println!("{doc:#?}");
3423
3424 let mut enc = NetdocEncoder::new();
3425 doc.encode_unsigned(&mut enc)?;
3426 sigs.encode_fields(&mut enc)?;
3427 let enc = enc.finish()?;
3428
3429 let mut exp: String = text.clone();
3430
3431 regsub(
3433 &mut exp,
3435 r#"^(shared-rand-.*)$"#,
3436 |c: ®ex::Captures| {
3437 let mut s = c[1].to_owned();
3438 regsub(&mut s, r#"="#, "");
3439 s
3440 },
3441 );
3442
3443 regsub(
3446 &mut exp,
3448 r#"^(client|server)-versions (.+)$"#,
3449 |c: ®ex::Captures| -> String {
3450 format!(
3451 "{}-versions {}",
3452 &c[1],
3453 iter_join(",", c[2].split(',').sorted()),
3454 )
3455 },
3456 );
3457
3458 let mut regsub = |re, repl| regsub(&mut exp, re, repl);
3459
3460 regsub(
3462 r#"^((?:client|server)-versions) $"#,
3464 "$1",
3465 );
3466
3467 regsub(
3469 r#"^(shared-rand-commit .*) $"#,
3471 "$1",
3472 );
3473
3474 regsub(
3478 r#"(?x)
3479 ( ^ r\ .* \n ) # ( r ) $1, part before where we want to put m's
3480 ( (?: .* \n )*? ) # (.*? ) $2, the rest, before the m's
3481 ( (?: m\ .* \n )+ ) # ( m+ ) $3, one or more m's
3482 "#,
3483 r#"$1$3$2"#,
3484 );
3485
3486 UV::adjust_exp(&mut exp);
3487
3488 assert_eq_or_diff!(&exp, &enc);
3489
3490 Ok(())
3491 }
3492
3493 trait MungeForRoundtrip {
3494 fn adjust_exp(exp: &mut String);
3496 }
3497
3498 #[cfg(feature = "retain-unknown")]
3502 #[test]
3503 fn roundtrip_netstatus_plain() -> anyhow::Result<()> {
3504 roundtrip_netstatus::<plain::NetworkStatusUnverified, _, _>(
3505 "testdata2/cached-consensus",
3506 plain::NetworkStatusUnverified::verify,
3507 Duration::ZERO,
3508 )
3509 }
3510
3511 impl MungeForRoundtrip for plain::NetworkStatusUnverified {
3512 fn adjust_exp(exp: &mut String) {
3513 let mut regsub = |re, repl| regsub(exp, re, repl);
3514
3515 regsub(
3518 r#"^network-status-version 3$"#,
3519 "network-status-version 3 ns",
3520 );
3521
3522 regsub(
3526 r#"^(r \S+ \S+ \S+) \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"#,
3527 "$1 2000-01-01 00:00:01",
3528 );
3529 }
3530 }
3531
3532 #[cfg(feature = "retain-unknown")]
3533 #[test]
3534 fn roundtrip_netstatus_md() -> anyhow::Result<()> {
3535 roundtrip_netstatus::<md::NetworkStatusUnverified, _, _>(
3536 "testdata2/cached-microdesc-consensus",
3537 md::NetworkStatusUnverified::verify,
3538 Duration::ZERO,
3539 )
3540 }
3541
3542 impl MungeForRoundtrip for md::NetworkStatusUnverified {
3543 fn adjust_exp(exp: &mut String) {
3544 let mut regsub = |re, repl| regsub(exp, re, repl);
3545
3546 regsub(
3552 r#"^(r \S+ \S+) \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"#,
3553 "$1 2000-01-01 00:00:01",
3554 );
3555 }
3556 }
3557
3558 #[cfg(feature = "retain-unknown")]
3559 #[test]
3560 fn roundtrip_netstatus_vote() -> anyhow::Result<()> {
3561 roundtrip_netstatus::<vote::NetworkStatusUnverified, _, _>(
3562 "testdata2/v3-status-votes--1",
3563 |doc, trusted, _| {
3564 vote::NetworkStatusUnverified::verify(
3565 doc,
3566 &mut VoteVerifier::new(trusted.iter().copied()),
3567 )
3568 },
3569 Duration::from_secs(20),
3570 )
3571 }
3572
3573 impl MungeForRoundtrip for vote::NetworkStatusUnverified {
3574 fn adjust_exp(exp: &mut String) {
3575 let stats_massage_entry = |e: &str| {
3579 let mut e = e.to_owned();
3580 if e.contains('.') {
3581 regsub(
3582 &mut e,
3583 r#"(?x)^ ( (?:wfu) = [0-9.]*? )( \.? 0+ ) $"#,
3585 "$1",
3586 );
3587 }
3588 e
3589 };
3590
3591 regsub(exp, r#"^stats (.+)$"#, |c: ®ex::Captures| -> String {
3593 format!(
3594 "stats {}",
3595 iter_join(" ", c[1].split(' ').sorted().map(stats_massage_entry)),
3596 )
3597 });
3598
3599 let mut regsub = |re: &_, repl| regsub(exp, re, repl);
3600
3601 regsub(
3603 r#"(?x)
3604 ^ (recommended-relay-protocols\ .*) \n
3605 (recommended-client-protocols\ .*) \n
3606 (required-relay-protocols\ .*) \n
3607 (required-client-protocols\ .*) \n
3608 (known-flags .*)$ \n
3609 "#,
3610 r#"$5
3611$2
3612$1
3613$4
3614$3
3615"#,
3616 );
3617
3618 regsub(
3624 r#"(?x) ^ (voting-delay\ .*) \n
3625 (known-flags\ .*) \n"#,
3626 "$1
3627client-versions
3628server-versions
3629$2
3630",
3631 );
3632
3633 for missing_field in [
3636 "bandwidth-file-headers", "bandwidth-file-digest", "flag-thresholds", ] {
3640 regsub(&format!(r#"^{missing_field} .*\n"#), "");
3641 }
3642 }
3643 }
3644
3645 fn testdata_live(f: &str) -> String {
3646 let var = "TOR_NETDOC_TESTDATA_LIVE_PREFIX";
3650 let prefix = std::env::var_os(var)
3651 .map(|s| s.into_string().expect(var))
3652 .unwrap_or_else(|| "testdata-live/".into());
3653 format!("{prefix}{f}")
3654 }
3655
3656 #[allow(clippy::unnecessary_wraps)] fn unwrap_unverified_for_test<UV: NetdocParseableUnverified>(
3658 uv: UV,
3659 _ids: &[RsaIdentity],
3660 _certs: &[AuthCert],
3661 ) -> Result<TimeRangeBound<UV::Body>, std::convert::Infallible> {
3662 Ok(TimeRangeBound::new(uv.unwrap_unverified().0, ..))
3663 }
3664
3665 #[cfg(feature = "retain-unknown")]
3666 #[test]
3667 fn roundtrip_live_plain() -> anyhow::Result<()> {
3668 roundtrip_netstatus::<plain::NetworkStatusUnverified, _, _>(
3669 &testdata_live("consensus"),
3670 unwrap_unverified_for_test,
3671 Duration::ZERO,
3672 )
3673 }
3674
3675 #[cfg(feature = "retain-unknown")]
3676 #[test]
3677 fn roundtrip_live_md() -> anyhow::Result<()> {
3678 roundtrip_netstatus::<md::NetworkStatusUnverified, _, _>(
3679 &testdata_live("consensus-microdesc"),
3680 unwrap_unverified_for_test,
3681 Duration::ZERO,
3682 )
3683 }
3684
3685 #[cfg(feature = "retain-unknown")]
3686 #[test]
3687 fn roundtrip_live_vote() -> anyhow::Result<()> {
3688 roundtrip_netstatus::<vote::NetworkStatusUnverified, _, _>(
3689 &testdata_live("authority"),
3690 unwrap_unverified_for_test,
3691 Duration::ZERO,
3692 )
3693 }
3694
3695 #[cfg(feature = "retain-unknown")]
3696 #[test]
3697 fn sign_vote() -> anyhow::Result<()> {
3698 use crate::{
3699 encode::{encode_netdoc_fields, encode_netdoc_unsigned},
3700 test_support, testdata2,
3701 };
3702 use tor_llcrypto::pk::rsa;
3703
3704 let authcert = parse_netdoc::<AuthCertUnverified>(
3705 &ParseInput::new(testdata2::keys::AUTHORITY_CERTIFICATE, "authcert")
3706 .retain_unknown_values(),
3707 )?;
3708 let authcert = authcert.unwrap_unverified().0;
3709 let authority_id = authcert.fingerprint;
3710
3711 let doc = test_support::find_vote_by_authority_id(
3712 &ParseInput::new(testdata2::V3_STATUS_VOTES, "v3-status-votes").retain_unknown_values(),
3713 *authority_id,
3714 )
3715 .0
3716 .unwrap_unverified()
3717 .0;
3718
3719 let body = encode_netdoc_unsigned([&doc])?;
3720
3721 let sk =
3722 rsa::KeyPair::from_der(pem::parse(testdata2::keys::AUTHORITY_SIGNING_KEY)?.contents())
3723 .unwrap();
3724
3725 for hash_algo in [
3726 DirectorySignatureHashAlgo::Sha1,
3727 DirectorySignatureHashAlgo::Sha256,
3728 ] {
3729 let directory_signature =
3730 Signature::sign_text(&sk, &body, hash_algo, authcert.key_ids())?;
3731
3732 let sig = encode_netdoc_fields(&vote::NetworkStatusSignatures {
3733 directory_signature,
3734 __non_exhaustive: (),
3735 })?;
3736
3737 let signed = body.clone() + &sig;
3738
3739 let _: vote::NetworkStatus = parse_netdoc::<vote::NetworkStatusUnverified>(
3740 &ParseInput::new(&signed, "<signed>"),
3741 )?
3742 .verify(&mut VoteVerifier::new([*authority_id]))?
3743 .dangerously_assume_timely();
3744 }
3745
3746 Ok(())
3747 }
3748}