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
127pub use rs::{RouterStatusMdDigestsVote, SoftwareVersion};
128
129pub use dir_source::{
130 ConsensusAuthoritySection, ConsensusAuthoritySectionConstructor, DirSource,
131 DirSourceConstructor, SupersededAuthorityKey,
132};
133
134define_constant_string! {
135 NetworkStatusVersion = "3";
145}
146
147define_constant_string! {
148 VoteStatusConsensus = "consensus";
152}
153
154define_constant_string! {
155 VoteStatusVote = "vote";
159}
160
161#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Default)]
175#[allow(clippy::exhaustive_structs)]
176pub struct IgnoredPublicationTimeSp;
177
178#[derive(Clone, Debug, PartialEq, Eq, Deftly)]
186#[derive_deftly(Constructor, NetdocEncodableFields, NetdocParseableFields)]
187#[derive_deftly(Lifetime)]
188#[allow(clippy::exhaustive_structs)]
189pub struct Lifetime {
190 #[deftly(constructor)]
197 #[deftly(netdoc(single_arg))]
198 pub valid_after: Iso8601TimeSp,
199 #[deftly(constructor)]
207 #[deftly(netdoc(single_arg))]
208 pub fresh_until: Iso8601TimeSp,
209 #[deftly(constructor)]
217 #[deftly(netdoc(single_arg))]
218 pub valid_until: Iso8601TimeSp,
219
220 #[doc(hidden)]
221 #[deftly(netdoc(skip))]
222 pub __non_exhaustive: (),
223}
224
225define_derive_deftly! {
226 Lifetime:
228
229 ${defcond FIELD not(approx_equal($fname, __non_exhaustive))}
230
231 impl Lifetime {
232 pub fn new(
234 $( ${when FIELD} $fname: time::SystemTime, )
235 ) -> crate::Result<Self> {
236 let self_ = Lifetime {
240 $( ${when FIELD} $fname: $fname.into(), )
241 __non_exhaustive: (),
242 };
243 if self_.valid_after < self_.fresh_until && self_.fresh_until < self_.valid_until {
244 Ok(self_)
245 } else {
246 Err(EK::InvalidLifetime.err())
247 }
248 }
249 $(
250 ${when FIELD}
251
252 ${fattrs doc}
253 pub fn $fname(&self) -> time::SystemTime {
254 *self.$fname
255 }
256 )
257 pub fn valid_at(&self, when: time::SystemTime) -> bool {
259 *self.valid_after <= when && when <= *self.valid_until
260 }
261
262 pub fn voting_period(&self) -> time::Duration {
267 let valid_after = self.valid_after();
268 let fresh_until = self.fresh_until();
269 fresh_until
270 .duration_since(valid_after)
271 .expect("Mis-formed lifetime")
272 }
273 }
274}
275use derive_deftly_template_Lifetime;
276
277#[derive(Debug, Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Copy)] #[derive(derive_more::From, derive_more::Into, derive_more::Display, derive_more::FromStr)]
289#[allow(clippy::exhaustive_structs)] pub struct ConsensusMethod(pub u32);
291impl NormalItemArgument for ConsensusMethod {}
292
293#[derive(Debug, Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Deftly)]
300#[derive_deftly(ItemValueEncodable, ItemValueParseable)]
301#[non_exhaustive]
302pub struct ConsensusMethods {
303 pub methods: BTreeSet<ConsensusMethod>,
305}
306
307pub mod consensus_methods_comma_separated {
312 use super::*;
313 use parse2::ArgumentError as AE;
314 use std::result::Result;
315
316 pub fn from_args<'s>(args: &mut ArgumentStream<'s>) -> Result<ConsensusMethods, AE> {
318 let mut methods = BTreeSet::new();
319 for ent in args.next().ok_or(AE::Missing)?.split(',') {
320 let ent = ent.parse().map_err(|_| AE::Invalid)?;
321 if !methods.insert(ent) {
322 return Err(AE::Invalid);
323 }
324 }
325 Ok(ConsensusMethods { methods })
326 }
327
328 pub fn write_arg_onto(self_: &ConsensusMethods, out: &mut ItemEncoder) -> Result<(), Bug> {
330 out.args_raw_string(&iter_join(",", &self_.methods));
331 Ok(())
332 }
333}
334
335#[derive(Debug, Clone, Eq, PartialEq, Hash, Copy, Deftly)]
339#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
340#[allow(clippy::exhaustive_structs)]
341pub struct VotingDelay {
342 #[deftly(constructor)]
344 pub vote_seconds: u32,
345
346 #[deftly(constructor)]
348 pub dist_seconds: u32,
349
350 #[doc(hidden)]
351 #[deftly(netdoc(skip))]
352 pub __non_exhaustive: (),
353}
354
355#[derive(Debug, Clone, Educe, Eq, PartialEq)]
381#[educe(Default)]
382pub struct NetParams<T> {
383 params: HashMap<String, T>,
385}
386
387impl<T> NetParams<T> {
388 #[allow(unused)]
390 pub fn new() -> Self {
391 NetParams {
392 params: HashMap::new(),
393 }
394 }
395 pub fn get<A: AsRef<str>>(&self, v: A) -> Option<&T> {
397 self.params.get(v.as_ref())
398 }
399 pub fn iter(&self) -> impl Iterator<Item = (&String, &T)> {
401 self.params.iter()
402 }
403 pub fn set(&mut self, k: String, v: T) {
405 self.params.insert(k, v);
406 }
407}
408
409impl<K: Into<String>, T> FromIterator<(K, T)> for NetParams<T> {
410 fn from_iter<I: IntoIterator<Item = (K, T)>>(i: I) -> Self {
411 NetParams {
412 params: i.into_iter().map(|(k, v)| (k.into(), v)).collect(),
413 }
414 }
415}
416
417impl<T> std::iter::Extend<(String, T)> for NetParams<T> {
418 fn extend<I: IntoIterator<Item = (String, T)>>(&mut self, iter: I) {
419 self.params.extend(iter);
420 }
421}
422
423impl<'de, T> Deserialize<'de> for NetParams<T>
424where
425 T: Deserialize<'de>,
426{
427 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
428 where
429 D: Deserializer<'de>,
430 {
431 let params = HashMap::deserialize(deserializer)?;
432 Ok(NetParams { params })
433 }
434}
435
436#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize, Deftly)]
445#[derive_deftly(Constructor)]
446#[allow(clippy::exhaustive_structs)]
447pub struct ProtoStatus {
448 pub recommended: Protocols,
453
454 pub required: Protocols,
459
460 #[doc(hidden)]
461 #[serde(skip)]
462 pub __non_exhaustive: (),
463}
464
465impl ProtoStatus {
466 pub fn check_protocols(
476 &self,
477 supported_protocols: &Protocols,
478 ) -> Result<(), ProtocolSupportError> {
479 let missing_required = self.required.difference(supported_protocols);
481 if !missing_required.is_empty() {
482 return Err(ProtocolSupportError::MissingRequired(missing_required));
483 }
484 let missing_recommended = self.recommended.difference(supported_protocols);
485 if !missing_recommended.is_empty() {
486 return Err(ProtocolSupportError::MissingRecommended(
487 missing_recommended,
488 ));
489 }
490
491 Ok(())
492 }
493}
494
495#[derive(Clone, Debug, thiserror::Error)]
497#[cfg_attr(test, derive(PartialEq))]
498#[non_exhaustive]
499pub enum ProtocolSupportError {
500 #[error("Required protocols are not implemented: {0}")]
502 MissingRequired(Protocols),
503
504 #[error("Recommended protocols are not implemented: {0}")]
508 MissingRecommended(Protocols),
509}
510
511impl ProtocolSupportError {
512 pub fn should_shutdown(&self) -> bool {
514 matches!(self, Self::MissingRequired(_))
515 }
516}
517
518impl HasKind for ProtocolSupportError {
519 fn kind(&self) -> tor_error::ErrorKind {
520 tor_error::ErrorKind::SoftwareDeprecated
521 }
522}
523
524#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, Deftly)]
531#[derive_deftly(Constructor)]
532#[allow(clippy::exhaustive_structs)]
533pub struct ProtoStatuses {
534 pub client: ProtoStatus,
536
537 pub relay: ProtoStatus,
539
540 #[doc(hidden)]
541 #[serde(skip)]
542 pub __non_exhaustive: (),
543}
544
545impl ProtoStatuses {
546 pub fn client(&self) -> &ProtoStatus {
548 &self.client
549 }
550
551 pub fn relay(&self) -> &ProtoStatus {
553 &self.relay
554 }
555}
556
557#[derive(Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd)] #[derive(derive_more::Deref, derive_more::Into)]
578pub struct RecommendedTorVersions(BTreeSet<String>);
579
580#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
582#[non_exhaustive]
583pub enum InvalidRecommendedTorVersions {
584 #[error("version {_0:?} contains whitespace")]
586 ContainsWhitespace(String),
587
588 #[error("version {_0:?} is repeated")]
590 Repeated(String),
591}
592
593impl RecommendedTorVersions {
594 pub fn new_unknown() -> Self {
596 Self::default()
597 }
598
599 pub fn is_known(&self) -> bool {
605 !self.is_empty()
606 }
607
608 #[allow(clippy::should_implement_trait)] pub fn from_iter<I, S>(i: I) -> Result<Self, InvalidRecommendedTorVersions>
611 where
612 I: IntoIterator<Item = S>,
613 S: AsRef<str>,
614 {
615 let mut set = BTreeSet::new();
616 for v in i {
617 let v = v.as_ref();
618 if v.is_empty() {
619 continue;
620 }
621 if v.chars().any(|c| c.is_whitespace()) {
622 return Err(InvalidRecommendedTorVersions::ContainsWhitespace(
623 v.to_owned(),
624 ));
625 }
626 if !set.insert(v.to_owned()) {
627 return Err(InvalidRecommendedTorVersions::Repeated(v.to_owned()));
628 }
629 }
630 Ok(RecommendedTorVersions(set))
631 }
632}
633
634impl FromStr for RecommendedTorVersions {
635 type Err = InvalidRecommendedTorVersions;
636 fn from_str(s: &str) -> Result<Self, InvalidRecommendedTorVersions> {
637 Self::from_iter(s.split(','))
638 }
639}
640
641impl Display for RecommendedTorVersions {
642 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
643 write!(f, "{}", iter_join(",", &self.0))
644 }
645}
646
647impl NormalItemArgument for RecommendedTorVersions {}
648
649impl ItemValueEncodable for RecommendedTorVersions {
650 fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
651 out.args_raw_string(self);
652 Ok(())
653 }
654}
655
656impl ItemValueParseable for RecommendedTorVersions {
657 fn from_unparsed(mut item: UnparsedItem) -> Result<Self, ErrorProblem> {
658 const FIELD: &str = "versions";
659 item.check_no_object()?;
660 let args = item.args_mut();
661 let arg = args.next().unwrap_or("");
662 arg.parse::<Self>()
663 .map_err(|_| args.handle_error(FIELD, ArgumentError::Invalid))
664 }
665}
666
667#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
675#[allow(clippy::exhaustive_enums)]
676pub enum ConsensusFlavor {
677 Microdesc,
680 Plain,
685}
686
687impl ConsensusFlavor {
688 pub fn name(&self) -> &'static str {
690 match self {
691 ConsensusFlavor::Plain => "ns", ConsensusFlavor::Microdesc => "microdesc",
693 }
694 }
695 pub fn from_opt_name(name: Option<&str>) -> crate::Result<Self> {
700 match name {
701 Some("microdesc") => Ok(ConsensusFlavor::Microdesc),
702 Some("ns") | None => Ok(ConsensusFlavor::Plain),
703 Some(other) => {
704 Err(EK::BadDocumentType.with_msg(format!("unrecognized flavor {:?}", other)))
705 }
706 }
707 }
708}
709
710define_derive_deftly! {
711 DirectorySignaturesHashesAccu:
719
720 ${define FNAME ${paste ${snake_case $vname}} }
721
722 #[derive(Clone, Copy, Default, Debug, Eq, PartialEq, Deftly)]
724 #[derive_deftly(AsMutSelf)]
725 #[non_exhaustive]
726 pub struct DirectorySignaturesHashesAccu {
727 $(
728 ${vattrs doc}
729 pub $FNAME: Option<[u8; ${vmeta(hash_len) as expr}]>,
730 )
731 }
732
733 impl DirectorySignaturesHashesAccu {
734 fn update_from(
736 &mut self,
737 algo: &DigestAlgoInSignature,
738 body: &SignatureHashInputs,
739 ) {
740 ${define HASH {
743 self.$UPDATE.get_or_insert_with(|| {
745 let mut h = tor_llcrypto::d::$ALGO::new();
746 h.update(body.body().body());
747 h.update(body.signature_item_kw_spc);
748 h.finalize().into()
749 });
750 }}
751
752 match &**algo {
753 $(
754 Some(KeywordOrString::Known($vtype)) => {
755 ${define UPDATE $FNAME}
756 ${define ALGO $vname}
757 $HASH
758 }
759 )
760 None => {
761 ${define UPDATE sha1}
762 ${define ALGO Sha1}
763 $HASH
764 }
765 Some(KeywordOrString::Unknown(..)) => {}
766 }
767 }
768
769 fn hash_slice_for_verification(
774 &self,
775 algo: &DigestAlgoInSignature,
776 ) -> Option<&[u8]> {
777 match &**algo {
778 $(
779 Some(KeywordOrString::Known($vtype)) => Some(self.$FNAME.as_ref()?),
780 )
781 None => Some(self.sha1.as_ref()?),
782 Some(KeywordOrString::Unknown(..)) => None,
783 }
784 }
785 }
786}
787
788#[derive(Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, Deftly)]
790#[derive_deftly(DirectorySignaturesHashesAccu)]
791#[non_exhaustive]
792#[strum(serialize_all = "snake_case")]
793pub enum DirectorySignatureHashAlgo {
794 #[deftly(hash_len = "20")]
796 Sha1,
797 #[deftly(hash_len = "32")]
799 Sha256,
800}
801
802#[derive(Debug, Clone, derive_more::Deref, derive_more::DerefMut)]
814#[allow(clippy::exhaustive_structs)]
815pub struct DigestAlgoInSignature(pub Option<KeywordOrString<DirectorySignatureHashAlgo>>);
816
817impl ItemArgumentParseable for DigestAlgoInSignature {
818 fn from_args<'s>(args: &mut ArgumentStream<'s>) -> Result<Self, ArgumentError> {
819 let v = if args
820 .clone()
821 .next()
822 .and_then(|s| s.chars().all(|c| c.is_ascii_hexdigit()).then_some(()))
826 .is_some()
827 {
828 None
830 } else {
831 Some(KeywordOrString::from_args(args)?)
832 };
833 Ok(DigestAlgoInSignature(v))
834 }
835}
836impl ItemArgument for DigestAlgoInSignature {
837 fn write_arg_onto(&self, out: &mut ItemEncoder<'_>) -> Result<(), Bug> {
838 if let Some(y) = &self.0 {
839 y.write_arg_onto(out)?;
840 }
841 Ok(())
842 }
843}
844impl DigestAlgoInSignature {
845 pub fn algorithm(&self) -> &KeywordOrString<DirectorySignatureHashAlgo> {
849 self.as_ref()
850 .unwrap_or(&KeywordOrString::Known(DirectorySignatureHashAlgo::Sha1))
851 }
852}
853
854impl NormalItemArgument for DirectorySignatureHashAlgo {}
855
856#[derive(Debug, Clone, Deftly)]
861#[derive_deftly(ItemValueEncodable, ItemValueParseable)]
862#[non_exhaustive]
863pub struct Signature {
864 pub digest_algo: DigestAlgoInSignature,
869 #[deftly(netdoc(with = authcert::keyids_directory_signature_args))]
872 pub key_ids: AuthCertKeyIds,
873 #[deftly(netdoc(object(label = "SIGNATURE"), with = types::raw_data_object))]
875 pub signature: Vec<u8>,
876}
877
878impl SignatureItemParseable for Signature {
879 type HashAccu = DirectorySignaturesHashesAccu;
880
881 fn from_unparsed_and_body(
882 item: UnparsedItem,
883 body: &SignatureHashInputs<'_>,
884 hash: &mut Self::HashAccu,
885 ) -> Result<Self, ErrorProblem> {
886 let signature = Signature::from_unparsed(item)?;
887 hash.update_from(&signature.digest_algo, body);
888 Ok(signature)
889 }
890}
891
892#[derive(Debug, Clone)]
898#[non_exhaustive]
899pub struct SignatureGroup {
900 pub hashes: DirectorySignaturesHashesAccu,
906 pub signatures: Vec<Signature>,
908}
909
910#[derive(Clone, Debug, thiserror::Error)]
921#[allow(clippy::exhaustive_enums)]
922pub enum ConsensusVerifiabilityError {
923 #[error("consensus not signed by enough authorities")]
925 InsufficientTrustedSigners,
926
927 #[error("missing auth certs mean we could not verify enough consensuis signatures (need at least {deficit} more, out of {} that are missing)", missing.len())]
929 MissingAuthCerts {
930 deficit: usize,
932 missing: HashSet<AuthCertKeyIds>,
934 },
935}
936
937#[derive(Clone, Debug, thiserror::Error)]
949#[non_exhaustive]
950pub enum ConsensusVerifyFailed {
951 #[error("certs/sigs insufficient")]
953 CertificationInsufficient(#[from] ConsensusVerifiabilityError),
954
955 #[error("invalid signature")]
957 InvalidSignature(#[source] VerifyFailed),
962}
963
964#[derive(Clone, Debug, thiserror::Error)]
974#[non_exhaustive]
975pub enum VoteVerifyFailed {
976 #[error("invalid signature")]
978 InvalidSignature(#[source] VerifyFailed),
983
984 #[error("unparseable authcert")]
986 AuthCertParseError(#[source] parse2::ParseError),
987
988 #[error("authcert not valid for vote period")]
990 AuthCertWrongValidity(#[source] tor_checkable::TimeValidityError),
991
992 #[error("wrong authcert")]
994 AuthCertWrongAuthority,
995}
996
997#[derive(
999 Debug, Clone, Copy, Eq, PartialEq, derive_more::From, derive_more::Into, derive_more::AsRef,
1000)]
1001pub struct SharedRandVal([u8; 32]);
1003
1004#[derive(Debug, Clone, Deftly)]
1007#[non_exhaustive]
1008#[derive_deftly(ItemValueEncodable, ItemValueParseable)]
1009pub struct SharedRandStatus {
1010 pub n_reveals: u8,
1012 pub value: SharedRandVal,
1019
1020 pub timestamp: Option<Iso8601TimeNoSp>,
1024}
1025
1026#[derive(Debug, Clone, Default, Deftly)]
1033#[derive_deftly(Constructor, NetdocEncodableFields, NetdocParseableFields)]
1034#[allow(clippy::exhaustive_structs)]
1035pub struct SharedRandStatuses {
1036 pub shared_rand_previous_value: Option<SharedRandStatus>,
1038
1039 pub shared_rand_current_value: Option<SharedRandStatus>,
1041
1042 #[doc(hidden)]
1043 #[deftly(netdoc(skip))]
1044 pub __non_exhaustive: (),
1045}
1046
1047#[derive(Debug, Clone)]
1104pub struct RelayWeightsItem {
1105 effective: RelayWeight,
1107
1108 params: Unknown<Option<NetParams<u32>>>,
1110}
1111
1112#[derive(Debug, Clone, Deftly)]
1114#[derive_deftly(NetdocEncodableFields, NetdocParseableFields)]
1115#[allow(clippy::exhaustive_structs)] pub struct VoteRelayWeightsItem {
1117 pub w: Option<NetParams<u32>>,
1119}
1120
1121#[non_exhaustive]
1125#[derive(Debug, Clone, Copy)]
1126pub enum RelayWeight {
1127 Unmeasured(u32),
1129 Measured(u32),
1131}
1132
1133#[derive(Debug, Clone, thiserror::Error)]
1135#[non_exhaustive]
1136pub enum InvalidRelayWeights {
1137 #[error("invalid value for Unmeasured")]
1139 InvalidUnmeasured,
1140}
1141
1142#[deprecated = "renamed to ConsensusAuthorityEntry"]
1144pub type ConsensusVoterInfo = ConsensusAuthorityEntry;
1145
1146pub type PlainAuthorityEntry = ConsensusAuthorityEntry;
1148pub type MdAuthorityEntry = ConsensusAuthorityEntry;
1150
1151#[derive(Debug, Clone, Deftly)]
1161#[derive_deftly(Constructor, NetdocEncodable, NetdocParseable)]
1162#[allow(clippy::exhaustive_structs)]
1163pub struct ConsensusAuthorityEntry {
1164 #[deftly(constructor)]
1166 pub dir_source: DirSource,
1167
1168 #[deftly(constructor)]
1174 pub contact: ContactInfo,
1175
1176 #[deftly(netdoc(single_arg))]
1183 #[deftly(constructor)]
1184 pub vote_digest: B16U,
1185
1186 #[doc(hidden)]
1187 #[deftly(netdoc(skip))]
1188 pub __non_exhaustive: (),
1189}
1190
1191#[derive(Debug, Clone, Deftly)]
1197#[derive_deftly(Constructor, NetdocEncodable, NetdocParseable)]
1198#[allow(clippy::exhaustive_structs)]
1199pub struct VoteAuthorityEntry {
1200 #[deftly(constructor)]
1202 pub dir_source: DirSource,
1203
1204 #[deftly(constructor)]
1206 pub contact: ContactInfo,
1207
1208 #[deftly(netdoc(single_arg))]
1212 pub legacy_dir_key: Option<Fingerprint>,
1213
1214 pub shared_rand_participate: Option<SharedRandParticipate>,
1218
1219 pub shared_rand_commit: Vec<SharedRandCommit>,
1223
1224 #[deftly(netdoc(flatten))]
1226 pub shared_rand: SharedRandStatuses,
1227
1228 #[doc(hidden)]
1229 #[deftly(netdoc(skip))]
1230 pub __non_exhaustive: (),
1231}
1232
1233#[derive(Debug, Clone, Deftly)]
1243#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
1244#[allow(clippy::exhaustive_structs)]
1245pub struct SharedRandParticipate {
1246 #[doc(hidden)]
1247 #[deftly(netdoc(skip))]
1248 pub __non_exhaustive: (),
1249}
1250
1251#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deftly)]
1255#[allow(clippy::exhaustive_enums)]
1257pub enum SharedRandCommit {
1258 V1(SharedRandCommitV1),
1260
1261 Unknown {},
1264}
1265
1266#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deftly)]
1275#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
1276#[allow(clippy::exhaustive_structs)]
1277pub struct SharedRandCommitV1 {
1278 #[deftly(constructor)]
1281 h_kp_auth_id_rsa: Fingerprint,
1282
1283 #[deftly(constructor)]
1291 commit: FixedB64<40>,
1292
1293 reveal: Option<FixedB64<40>>,
1298
1299 #[doc(hidden)]
1300 #[deftly(netdoc(skip))]
1301 pub __non_exhaustive: (),
1302}
1303
1304impl SharedRandCommitV1 {
1305 const FIXED_ARGUMENTS: &[&str] = &["1", "sha3-256"];
1307}
1308impl ItemValueEncodable for SharedRandCommit {
1309 fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
1310 match self {
1311 SharedRandCommit::V1(values) => {
1312 for fixed in SharedRandCommitV1::FIXED_ARGUMENTS {
1313 out.args_raw_string(fixed);
1314 }
1315 values.write_item_value_onto(out)
1316 }
1317 SharedRandCommit::Unknown {} => Err(internal!("encoding SharedRandCommit::Unknown")),
1318 }
1319 }
1320}
1321impl ItemValueParseable for SharedRandCommit {
1322 fn from_unparsed(mut item: UnparsedItem<'_>) -> Result<Self, ErrorProblem> {
1323 let mut fixed = SharedRandCommitV1::FIXED_ARGUMENTS.iter().copied();
1324 let args = item.args_mut();
1325 let version = args
1326 .next()
1327 .ok_or_else(|| args.handle_error("version", ArgumentError::Missing))?;
1328 if version != fixed.next().expect("nonempty") {
1329 return Ok(SharedRandCommit::Unknown {});
1330 }
1331 for exp in fixed {
1332 let got = args
1333 .next()
1334 .ok_or_else(|| args.handle_error(exp, ArgumentError::Missing))?;
1335 if got != exp {
1336 Err(args.handle_error(exp, ArgumentError::Invalid))?;
1337 }
1338 }
1339 let values = SharedRandCommitV1::from_unparsed(item)?;
1340 Ok(SharedRandCommit::V1(values))
1341 }
1342}
1343
1344define_derive_deftly! {
1347 VoteAuthoritySection:
1359
1360 ${defcond F_NORMAL not(fmeta(netdoc(skip)))}
1361
1362 impl NetdocParseable for VoteAuthoritySection {
1363 fn doctype_for_error() -> &'static str {
1364 "vote.authority.section"
1365 }
1366 fn is_intro_item_keyword(kw: KeywordRef<'_>) -> bool {
1367 VoteAuthorityEntry::is_intro_item_keyword(kw)
1368 }
1369 fn is_structural_keyword(kw: KeywordRef<'_>) -> Option<IsStructural> {
1370 $(
1371 ${when F_NORMAL}
1372 if let y @ Some(_) = $ftype::is_structural_keyword(kw) {
1373 return y;
1374 }
1375 )
1376 None
1377 }
1378 fn from_items<'s>(
1379 input: &mut ItemStream<'s>,
1380 stop_outer: stop_at!(),
1381 ) -> Result<Self, ErrorProblem> {
1382 let stop_inner = stop_outer
1383 $(
1384 ${when F_NORMAL}
1385 | StopAt($ftype::is_intro_item_keyword)
1386 )
1387 ;
1388 Ok(VoteAuthoritySection { $(
1389 ${when F_NORMAL}
1390 $fname: NetdocParseable::from_items(input, stop_inner)?,
1391 )
1392 __non_exhaustive: (),
1393 })
1394 }
1395 }
1396
1397 impl NetdocEncodable for VoteAuthoritySection {
1398 fn encode_unsigned(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
1399 $(
1400 ${when F_NORMAL}
1401 self.$fname.encode_unsigned(out)?;
1402 )
1403 Ok(())
1404 }
1405 }
1406}
1407
1408#[derive(Deftly, Clone, Debug)]
1415#[derive_deftly(VoteAuthoritySection, Constructor)]
1416#[allow(clippy::exhaustive_structs)]
1417pub struct VoteAuthoritySection {
1418 #[deftly(constructor)]
1420 pub authority: VoteAuthorityEntry,
1421
1422 #[deftly(constructor)]
1424 pub cert: EmbeddedCert<AuthCert, EncodedAuthCert>,
1425
1426 #[doc(hidden)]
1427 #[deftly(netdoc(skip))]
1428 pub __non_exhaustive: (),
1429}
1430
1431#[derive(Debug, Clone, Deftly)]
1437#[derive_deftly(Constructor, NetdocEncodableFields, NetdocParseableFields)]
1438#[allow(clippy::exhaustive_structs)]
1439pub struct ConsensusFooterFields {
1440 #[deftly(netdoc(default))]
1444 pub bandwidth_weights: NetParams<i32>,
1445
1446 #[doc(hidden)]
1447 #[deftly(netdoc(skip))]
1448 pub __non_exhaustive: (),
1449}
1450
1451pub type MdConsensus = md::Consensus;
1454
1455pub type UnvalidatedMdConsensus = md::UnvalidatedConsensus;
1458
1459pub type UncheckedMdConsensus = md::UncheckedConsensus;
1462
1463pub type PlainConsensus = plain::Consensus;
1466
1467pub type UnvalidatedPlainConsensus = plain::UnvalidatedConsensus;
1470
1471pub type UncheckedPlainConsensus = plain::UncheckedConsensus;
1474
1475decl_keyword! {
1476 #[non_exhaustive]
1481 #[allow(missing_docs)]
1482 pub NetstatusKwd {
1483 "network-status-version" => NETWORK_STATUS_VERSION,
1485 "vote-status" => VOTE_STATUS,
1486 "consensus-methods" => CONSENSUS_METHODS,
1487 "consensus-method" => CONSENSUS_METHOD,
1488 "published" => PUBLISHED,
1489 "valid-after" => VALID_AFTER,
1490 "fresh-until" => FRESH_UNTIL,
1491 "valid-until" => VALID_UNTIL,
1492 "voting-delay" => VOTING_DELAY,
1493 "client-versions" => CLIENT_VERSIONS,
1494 "server-versions" => SERVER_VERSIONS,
1495 "known-flags" => KNOWN_FLAGS,
1496 "flag-thresholds" => FLAG_THRESHOLDS,
1497 "recommended-client-protocols" => RECOMMENDED_CLIENT_PROTOCOLS,
1498 "required-client-protocols" => REQUIRED_CLIENT_PROTOCOLS,
1499 "recommended-relay-protocols" => RECOMMENDED_RELAY_PROTOCOLS,
1500 "required-relay-protocols" => REQUIRED_RELAY_PROTOCOLS,
1501 "params" => PARAMS,
1502 "bandwidth-file-headers" => BANDWIDTH_FILE_HEADERS,
1503 "bandwidth-file-digest" => BANDWIDTH_FILE_DIGEST,
1504 "shared-rand-previous-value" => SHARED_RAND_PREVIOUS_VALUE,
1508 "shared-rand-current-value" => SHARED_RAND_CURRENT_VALUE,
1509
1510 "dir-source" => DIR_SOURCE,
1512 "contact" => CONTACT,
1513
1514 "legacy-dir-key" => LEGACY_DIR_KEY,
1516 "shared-rand-participate" => SHARED_RAND_PARTICIPATE,
1517 "shared-rand-commit" => SHARED_RAND_COMMIT,
1518
1519 "vote-digest" => VOTE_DIGEST,
1521
1522 "dir-key-certificate-version" => DIR_KEY_CERTIFICATE_VERSION,
1524
1525 "r" => RS_R,
1527 "a" => RS_A,
1528 "s" => RS_S,
1529 "v" => RS_V,
1530 "pr" => RS_PR,
1531 "w" => RS_W,
1532 "p" => RS_P,
1533 "m" => RS_M,
1534 "id" => RS_ID,
1535
1536 "directory-footer" => DIRECTORY_FOOTER,
1538 "bandwidth-weights" => BANDWIDTH_WEIGHTS,
1539 "directory-signature" => DIRECTORY_SIGNATURE,
1540 }
1541}
1542
1543static NS_HEADER_RULES_COMMON_: LazyLock<SectionRulesBuilder<NetstatusKwd>> = LazyLock::new(|| {
1545 use NetstatusKwd::*;
1546 let mut rules = SectionRules::builder();
1547 rules.add(NETWORK_STATUS_VERSION.rule().required().args(1..=2));
1548 rules.add(VOTE_STATUS.rule().required().args(1..));
1549 rules.add(VALID_AFTER.rule().required());
1550 rules.add(FRESH_UNTIL.rule().required());
1551 rules.add(VALID_UNTIL.rule().required());
1552 rules.add(VOTING_DELAY.rule().args(2..));
1553 rules.add(CLIENT_VERSIONS.rule());
1554 rules.add(SERVER_VERSIONS.rule());
1555 rules.add(KNOWN_FLAGS.rule().required());
1556 rules.add(RECOMMENDED_CLIENT_PROTOCOLS.rule().args(1..));
1557 rules.add(RECOMMENDED_RELAY_PROTOCOLS.rule().args(1..));
1558 rules.add(REQUIRED_CLIENT_PROTOCOLS.rule().args(1..));
1559 rules.add(REQUIRED_RELAY_PROTOCOLS.rule().args(1..));
1560 rules.add(PARAMS.rule());
1561 rules
1562});
1563static NS_HEADER_RULES_CONSENSUS: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1565 use NetstatusKwd::*;
1566 let mut rules = NS_HEADER_RULES_COMMON_.clone();
1567 rules.add(CONSENSUS_METHOD.rule().args(1..=1));
1568 rules.add(SHARED_RAND_PREVIOUS_VALUE.rule().args(2..));
1569 rules.add(SHARED_RAND_CURRENT_VALUE.rule().args(2..));
1570 rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1571 rules.build()
1572});
1573static NS_VOTERINFO_RULES_CONSENSUS: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1604 use NetstatusKwd::*;
1605 let mut rules = SectionRules::builder();
1606 rules.add(DIR_SOURCE.rule().required().args(6..));
1607 rules.add(CONTACT.rule().required());
1608 rules.add(VOTE_DIGEST.rule().required());
1609 rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1610 rules.build()
1611});
1612static NS_ROUTERSTATUS_RULES_COMMON_: LazyLock<SectionRulesBuilder<NetstatusKwd>> =
1614 LazyLock::new(|| {
1615 use NetstatusKwd::*;
1616 let mut rules = SectionRules::builder();
1617 rules.add(RS_A.rule().may_repeat().args(1..));
1618 rules.add(RS_S.rule().required());
1619 rules.add(RS_V.rule());
1620 rules.add(RS_PR.rule().required());
1621 rules.add(RS_W.rule());
1622 rules.add(RS_P.rule().args(2..));
1623 rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1624 rules
1625 });
1626
1627static NS_ROUTERSTATUS_RULES_PLAIN: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1629 use NetstatusKwd::*;
1630 let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
1631 rules.add(RS_R.rule().required().args(8..));
1632 rules.build()
1633});
1634
1635static NS_ROUTERSTATUS_RULES_MDCON: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1648 use NetstatusKwd::*;
1649 let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
1650 rules.add(RS_R.rule().required().args(6..));
1651 rules.add(RS_M.rule().required().args(1..));
1652 rules.build()
1653});
1654static NS_FOOTER_RULES: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1656 use NetstatusKwd::*;
1657 let mut rules = SectionRules::builder();
1658 rules.add(DIRECTORY_FOOTER.rule().required().no_args());
1659 rules.add(BANDWIDTH_WEIGHTS.rule());
1661 rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1662 rules.build()
1663});
1664
1665impl ProtoStatus {
1666 fn from_section(
1668 sec: &Section<'_, NetstatusKwd>,
1669 recommend_token: NetstatusKwd,
1670 required_token: NetstatusKwd,
1671 ) -> crate::Result<ProtoStatus> {
1672 fn parse(t: Option<&Item<'_, NetstatusKwd>>) -> crate::Result<Protocols> {
1674 if let Some(item) = t {
1675 item.args_as_str()
1676 .parse::<Protocols>()
1677 .map_err(|e| EK::BadArgument.at_pos(item.pos()).with_source(e))
1678 } else {
1679 Ok(Protocols::new())
1680 }
1681 }
1682
1683 let recommended = parse(sec.get(recommend_token))?;
1684 let required = parse(sec.get(required_token))?;
1685 Ok(ProtoStatus {
1686 recommended,
1687 required,
1688 __non_exhaustive: (),
1689 })
1690 }
1691
1692 pub fn required_protocols(&self) -> &Protocols {
1699 &self.required
1700 }
1701
1702 pub fn recommended_protocols(&self) -> &Protocols {
1707 &self.recommended
1708 }
1709}
1710
1711impl<T> std::str::FromStr for NetParams<T>
1712where
1713 T: std::str::FromStr,
1714 T::Err: std::error::Error,
1715{
1716 type Err = Error;
1717 fn from_str(s: &str) -> crate::Result<Self> {
1718 fn parse_pair<U>(p: &str) -> crate::Result<(String, U)>
1720 where
1721 U: std::str::FromStr,
1722 U::Err: std::error::Error,
1723 {
1724 let parts: Vec<_> = p.splitn(2, '=').collect();
1725 if parts.len() != 2 {
1726 return Err(EK::BadArgument
1727 .at_pos(Pos::at(p))
1728 .with_msg("Missing = in key=value list"));
1729 }
1730 let num = parts[1].parse::<U>().map_err(|e| {
1731 EK::BadArgument
1732 .at_pos(Pos::at(parts[1]))
1733 .with_msg(e.to_string())
1734 })?;
1735 Ok((parts[0].to_string(), num))
1736 }
1737
1738 let params = s
1739 .split(' ')
1740 .filter(|p| !p.is_empty())
1741 .map(parse_pair)
1742 .try_collect()?;
1743 Ok(NetParams { params })
1744 }
1745}
1746
1747impl FromStr for SharedRandVal {
1748 type Err = Error;
1749 fn from_str(s: &str) -> crate::Result<Self> {
1750 let val: B64 = s.parse()?;
1751 let val = SharedRandVal(val.into_array()?);
1752 Ok(val)
1753 }
1754}
1755impl Display for SharedRandVal {
1756 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1757 Display::fmt(&B64::from(Vec::from(self.0)), f)
1758 }
1759}
1760impl NormalItemArgument for SharedRandVal {}
1761
1762impl SharedRandStatus {
1763 fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Self> {
1766 match item.kwd() {
1767 NetstatusKwd::SHARED_RAND_PREVIOUS_VALUE | NetstatusKwd::SHARED_RAND_CURRENT_VALUE => {}
1768 _ => {
1769 return Err(Error::from(internal!(
1770 "wrong keyword {:?} on shared-random value",
1771 item.kwd()
1772 ))
1773 .at_pos(item.pos()));
1774 }
1775 }
1776 let n_reveals: u8 = item.parse_arg(0)?;
1777 let value: SharedRandVal = item.parse_arg(1)?;
1778 let timestamp = item.parse_optional_arg::<Iso8601TimeNoSp>(2)?;
1780 Ok(SharedRandStatus {
1781 n_reveals,
1782 value,
1783 timestamp,
1784 })
1785 }
1786
1787 pub fn value(&self) -> &SharedRandVal {
1789 &self.value
1790 }
1791
1792 pub fn timestamp(&self) -> Option<std::time::SystemTime> {
1794 self.timestamp.map(|t| t.0)
1795 }
1796}
1797
1798impl DirSource {
1799 fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Self> {
1801 if item.kwd() != NetstatusKwd::DIR_SOURCE {
1802 return Err(
1803 Error::from(internal!("Bad keyword {:?} on dir-source", item.kwd()))
1804 .at_pos(item.pos()),
1805 );
1806 }
1807 let nickname = item
1808 .required_arg(0)?
1809 .parse()
1810 .map_err(|e: InvalidNickname| {
1811 EK::BadArgument.at_pos(item.pos()).with_msg(e.to_string())
1812 })?;
1813 let identity = item.parse_arg(1)?;
1814 let hostname = item
1815 .required_arg(2)?
1816 .parse()
1817 .map_err(|e: InvalidInternetHost| {
1818 EK::BadArgument.at_pos(item.pos()).with_msg(e.to_string())
1819 })?;
1820 let ip = item.parse_arg(3)?;
1821 let dir_port = item.parse_arg(4)?;
1822 let or_port = item.parse_arg(5)?;
1823
1824 Ok(DirSource {
1825 nickname,
1826 identity,
1827 hostname,
1828 ip,
1829 dir_port,
1830 or_port,
1831 __non_exhaustive: (),
1832 })
1833 }
1834}
1835
1836impl ConsensusAuthorityEntry {
1837 fn from_section(sec: &Section<'_, NetstatusKwd>) -> crate::Result<ConsensusAuthorityEntry> {
1839 use NetstatusKwd::*;
1840 #[allow(clippy::unwrap_used)]
1843 let first = sec.first_item().unwrap();
1844 if first.kwd() != DIR_SOURCE {
1845 return Err(Error::from(internal!(
1846 "Wrong keyword {:?} at start of voter info",
1847 first.kwd()
1848 ))
1849 .at_pos(first.pos()));
1850 }
1851 let dir_source = DirSource::from_item(sec.required(DIR_SOURCE)?)?;
1852
1853 let contact = sec.required(CONTACT)?;
1854 let contact = contact
1860 .args_as_str()
1861 .parse()
1862 .map_err(|err: InvalidContactInfo| {
1863 EK::BadArgument
1864 .with_msg(err.to_string())
1865 .at_pos(contact.pos())
1866 })?;
1867
1868 let vote_digest = sec.required(VOTE_DIGEST)?.parse_arg::<B16U>(0)?;
1869
1870 Ok(ConsensusAuthorityEntry {
1871 dir_source,
1872 contact,
1873 vote_digest,
1874 __non_exhaustive: (),
1875 })
1876 }
1877}
1878
1879impl RelayWeightsItem {
1880 pub fn new_no_info() -> Self {
1884 RelayWeightsItem {
1885 effective: RelayWeight::default(),
1886 params: Unknown::new_discard(),
1887 }
1888 }
1889
1890 pub fn from_effective(effective: RelayWeight) -> Self {
1892 RelayWeightsItem {
1893 effective,
1894 params: Unknown::new_discard(),
1895 }
1896 }
1897
1898 pub fn effective(&self) -> RelayWeight {
1905 self.effective
1906 }
1907
1908 pub fn params(&self) -> Unknown<&Option<NetParams<u32>>> {
1916 self.params.as_ref()
1917 }
1918
1919 fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<RelayWeightsItem> {
1921 if item.kwd() != NetstatusKwd::RS_W {
1922 return Err(
1923 Error::from(internal!("Wrong keyword {:?} on W line", item.kwd()))
1924 .at_pos(item.pos()),
1925 );
1926 }
1927
1928 let params = item.args_as_str().parse()?;
1929 let effective = RelayWeight::from_net_params(¶ms).map_err(|e| e.at_pos(item.pos()))?;
1930
1931 Ok(RelayWeightsItem {
1932 effective,
1933 params: Unknown::new_discard(),
1934 })
1935 }
1936
1937 const KEYWORD: &str = "w";
1939}
1940
1941#[cfg(feature = "retain-unknown")]
1942impl Default for RelayWeightsItem {
1943 fn default() -> Self {
1944 RelayWeightsItem {
1945 effective: RelayWeight::default(),
1946 params: Unknown::Retained(None),
1947 }
1948 }
1949}
1950
1951impl RelayWeight {
1952 pub fn is_measured(&self) -> bool {
1954 matches!(self, RelayWeight::Measured(_))
1955 }
1956
1957 pub fn is_nonzero(&self) -> bool {
1959 !matches!(self, RelayWeight::Unmeasured(0) | RelayWeight::Measured(0))
1960 }
1961
1962 fn from_net_params(params: &NetParams<u32>) -> crate::Result<RelayWeight> {
1966 params
1967 .try_into()
1968 .map_err(|e: InvalidRelayWeights| EK::BadArgument.with_msg(e.to_string()))
1969 }
1970}
1971
1972impl Default for RelayWeight {
1973 fn default() -> RelayWeight {
1974 RelayWeight::Unmeasured(0)
1975 }
1976}
1977
1978impl TryFrom<&NetParams<u32>> for RelayWeight {
1979 type Error = InvalidRelayWeights;
1980
1981 fn try_from(params: &NetParams<u32>) -> Result<RelayWeight, InvalidRelayWeights> {
1982 let bw = params.params.get("Bandwidth");
1983 let unmeas = params.params.get("Unmeasured");
1984
1985 let bw = match bw {
1986 None => return Ok(RelayWeight::Unmeasured(0)),
1987 Some(b) => *b,
1988 };
1989
1990 match unmeas {
1991 None | Some(0) => Ok(RelayWeight::Measured(bw)),
1992 Some(1) => Ok(RelayWeight::Unmeasured(bw)),
1993 _ => Err(InvalidRelayWeights::InvalidUnmeasured),
1994 }
1995 }
1996}
1997
1998#[cfg(feature = "retain-unknown")]
1999impl TryFrom<NetParams<u32>> for RelayWeightsItem {
2000 type Error = InvalidRelayWeights;
2001
2002 fn try_from(params: NetParams<u32>) -> Result<RelayWeightsItem, InvalidRelayWeights> {
2003 Ok(RelayWeightsItem {
2004 effective: (¶ms).try_into()?,
2005 params: Unknown::Retained(Some(params)),
2006 })
2007 }
2008}
2009
2010mod parse2_impls {
2014 use super::*;
2015 pub(super) use parse2::{
2016 ArgumentError as AE, ArgumentStream, ErrorProblem as EP, ItemArgumentParseable,
2017 ItemValueParseable, NetdocParseableFields,
2018 };
2019 use std::result::Result;
2020
2021 impl<T: FromStr + NormalItemArgument> ItemValueParseable for NetParams<T>
2023 where
2024 T::Err: std::error::Error,
2025 {
2026 fn from_unparsed(item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
2027 item.check_no_object()?;
2028 item.args_copy()
2029 .into_remaining()
2030 .parse()
2031 .map_err(item.invalid_argument_handler("parameters"))
2032 }
2033 }
2034
2035 impl NetdocParseableFields for RelayWeightsItem {
2036 type Accumulator = Option<NetParams<u32>>;
2037
2038 fn is_item_keyword(kw: KeywordRef) -> bool {
2039 kw == Self::KEYWORD
2040 }
2041
2042 fn accumulate_item(acc: &mut Self::Accumulator, item: UnparsedItem) -> Result<(), EP> {
2043 if acc.is_some() {
2044 return Err(EP::ItemRepeated);
2045 }
2046 item.check_no_object()?;
2047 let params = NetParams::from_unparsed(item)?;
2048 *acc = Some(params);
2049 Ok(())
2050 }
2051
2052 fn finish(params: Self::Accumulator, items: &ItemStream) -> Result<Self, EP> {
2053 let effective = params
2054 .as_ref()
2055 .map(TryFrom::try_from)
2056 .transpose()
2057 .map_err(|_| EP::OtherBadDocument("invalid information in `w` item"))?
2058 .unwrap_or_default();
2059
2060 let params = items.parse_options().retain_unknown_values.map(|()| params);
2061
2062 Ok(RelayWeightsItem { effective, params })
2063 }
2064 }
2065
2066 impl ItemValueParseable for rs::SoftwareVersion {
2067 fn from_unparsed(mut item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
2068 item.check_no_object()?;
2069 item.args_mut()
2070 .into_remaining()
2071 .parse()
2072 .map_err(item.invalid_argument_handler("version"))
2073 }
2074 }
2075
2076 impl ItemArgumentParseable for IgnoredPublicationTimeSp {
2077 fn from_args(a: &mut ArgumentStream) -> Result<IgnoredPublicationTimeSp, AE> {
2078 let mut next_arg = || a.next().ok_or(AE::Missing);
2079 let _: &str = next_arg()?;
2080 let _: &str = next_arg()?;
2081 Ok(IgnoredPublicationTimeSp)
2082 }
2083 }
2084}
2085
2086mod encode_impls {
2090 use super::*;
2091 use std::result::Result;
2092 pub(crate) use {
2093 crate::encode::{ItemEncoder, ItemValueEncodable, NetdocEncodableFields},
2094 tor_error::Bug,
2095 };
2096
2097 impl NetdocEncodableFields for RelayWeightsItem {
2098 fn encode_fields(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
2099 if let Some(w) = self.params.as_ref().into_retained()? {
2100 w.write_item_value_onto(out.item(Self::KEYWORD))?;
2101 }
2102 Ok(())
2103 }
2104 }
2105
2106 impl<T: NormalItemArgument + Ord + Display> ItemValueEncodable for NetParams<T> {
2108 fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
2109 for (k, v) in self.iter().collect::<BTreeSet<_>>() {
2110 if k.is_empty()
2111 || k.chars()
2112 .any(|c| c.is_whitespace() || c.is_control() || c == '=')
2113 {
2114 return Err(bad_api_usage!(
2116 "tried to encode NetParms with unreasonable keyword {k:?}"
2117 ));
2118 }
2119 out.args_raw_string(&format_args!("{k}={v}"));
2120 }
2121 Ok(())
2122 }
2123 }
2124
2125 impl ItemValueEncodable for rs::SoftwareVersion {
2126 fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
2127 out.args_raw_string(self);
2128 Ok(())
2129 }
2130 }
2131
2132 impl ItemArgument for IgnoredPublicationTimeSp {
2133 fn write_arg_onto(&self, out: &mut ItemEncoder) -> Result<(), Bug> {
2134 out.args_raw_string(&"2000-01-01 00:00:01");
2135 Ok(())
2136 }
2137 }
2138}
2139
2140impl ConsensusFooterFields {
2141 fn from_section(sec: &Section<'_, NetstatusKwd>) -> crate::Result<ConsensusFooterFields> {
2143 use NetstatusKwd::*;
2144 sec.required(DIRECTORY_FOOTER)?;
2145
2146 let bandwidth_weights = sec
2147 .maybe(BANDWIDTH_WEIGHTS)
2148 .args_as_str()
2149 .unwrap_or("")
2150 .parse()?;
2151
2152 Ok(ConsensusFooterFields {
2153 bandwidth_weights,
2154 __non_exhaustive: (),
2155 })
2156 }
2157}
2158
2159mod proto_statuses_parse2_encode {
2163 use super::encode_impls::*;
2164 use super::parse2_impls::*;
2165 use super::*;
2166 use paste::paste;
2167 use std::result::Result;
2168
2169 macro_rules! impl_proto_statuses { { $( $rr:ident $cr:ident; )* } => { paste! {
2183 #[derive(Deftly)]
2184 #[derive_deftly(NetdocParseableFields)]
2185 #[allow(unreachable_pub)]
2187 pub struct ProtoStatusesParseHelper {
2188 $(
2189 #[deftly(netdoc(default))]
2190 [<$rr _ $cr _protocols>]: Protocols,
2191 )*
2192 }
2193
2194 pub use ProtoStatusesParseHelperNetdocParseAccumulator
2196 as ProtoStatusesNetdocParseAccumulator;
2197
2198 impl NetdocParseableFields for ProtoStatuses {
2199 type Accumulator = ProtoStatusesNetdocParseAccumulator;
2200 fn is_item_keyword(kw: KeywordRef<'_>) -> bool {
2201 ProtoStatusesParseHelper::is_item_keyword(kw)
2202 }
2203 fn accumulate_item(
2204 acc: &mut Self::Accumulator,
2205 item: UnparsedItem<'_>,
2206 ) -> Result<(), EP> {
2207 ProtoStatusesParseHelper::accumulate_item(acc, item)
2208 }
2209 fn finish(acc: Self::Accumulator, items: &ItemStream<'_>) -> Result<Self, EP> {
2210 let parse = ProtoStatusesParseHelper::finish(acc, items)?;
2211 let mut out = ProtoStatuses::default();
2212 $(
2213 out.$cr.$rr = parse.[< $rr _ $cr _protocols >];
2214 )*
2215 Ok(out)
2216 }
2217 }
2218
2219 impl NetdocEncodableFields for ProtoStatuses {
2220 fn encode_fields(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
2221 $(
2222 self.$cr.$rr.write_item_value_onto(
2223 out.item(concat!(stringify!($rr), "-", stringify!($cr), "-protocols"))
2224 )?;
2225 )*
2226 Ok(())
2227 }
2228 }
2229 } } }
2230
2231 impl_proto_statuses! {
2232 recommended client;
2233 recommended relay;
2234 required client;
2235 required relay;
2236 }
2237}
2238
2239impl Signature {
2240 fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Signature> {
2242 if item.kwd() != NetstatusKwd::DIRECTORY_SIGNATURE {
2243 return Err(Error::from(internal!(
2244 "Wrong keyword {:?} for directory signature",
2245 item.kwd()
2246 ))
2247 .at_pos(item.pos()));
2248 }
2249
2250 let (digest_algo, id_fp, sk_fp) = if item.n_args() > 2 {
2251 (
2252 item.required_arg(0)?,
2253 item.required_arg(1)?,
2254 item.required_arg(2)?,
2255 )
2256 } else {
2257 ("sha1", item.required_arg(0)?, item.required_arg(1)?)
2259 };
2260
2261 let digest_algo = digest_algo.to_string().parse().void_unwrap();
2262 let digest_algo = DigestAlgoInSignature(Some(digest_algo));
2263 let id_fingerprint = id_fp.parse::<Fingerprint>()?.into();
2264 let sk_fingerprint = sk_fp.parse::<Fingerprint>()?.into();
2265 let key_ids = AuthCertKeyIds {
2266 id_fingerprint,
2267 sk_fingerprint,
2268 };
2269 let signature = item.obj("SIGNATURE")?;
2270
2271 Ok(Signature {
2272 digest_algo,
2273 key_ids,
2274 signature,
2275 })
2276 }
2277
2278 fn matches_cert(&self, cert: &AuthCert) -> bool {
2281 cert.key_ids() == self.key_ids
2282 }
2283
2284 fn find_cert<'a>(&self, certs: &'a [AuthCert]) -> Option<&'a AuthCert> {
2287 certs.iter().find(|&c| self.matches_cert(c))
2288 }
2289
2290 fn signature_to_verify<'r>(
2294 &'r self,
2295 signed_digest: &'r [u8],
2296 certs: &'r [AuthCert],
2297 ) -> Option<ConsensusSignatureToVerify> {
2298 let cert = self.find_cert(certs)?;
2299 let key = cert.signing_key();
2300 Some(ConsensusSignatureToVerify {
2301 key,
2302 signed_digest,
2303 signature: &self.signature,
2304 })
2305 }
2306}
2307
2308impl EncodeOrd for Signature {
2309 fn encode_cmp(&self, other: &Self) -> std::cmp::Ordering {
2310 let k: for<'s> fn(&'_ Signature) -> (&'_ _, &'_ _) = |s| (&s.key_ids, &s.signature);
2311 Ord::cmp(&k(self), &k(other))
2312 }
2313}
2314
2315#[derive(Debug, Clone, Copy)]
2321struct ConsensusSignatureToVerify<'r> {
2322 key: &'r ll::pk::rsa::PublicKey,
2324
2325 signed_digest: &'r [u8],
2327
2328 signature: &'r [u8],
2330}
2331
2332pub(crate) struct SignatureVerifiedIfIntended {}
2341
2342impl<'r> ConsensusSignatureToVerify<'r> {
2343 fn verify(self) -> Result<SignatureVerifiedIfIntended, VerifyFailed> {
2346 self.key.verify(self.signed_digest, self.signature)?;
2347 Ok(SignatureVerifiedIfIntended {})
2348 }
2349}
2350
2351#[derive(Debug, Clone, Copy)]
2355pub(crate) enum VerifyGeneralTrustedAuthorities<'r> {
2356 TrustThese {
2358 trusted: &'r [RsaIdentity],
2360 },
2361
2362 AnyOneOfThese {
2364 trusted: &'r [RsaIdentity],
2366 },
2367
2368 HazardouslyAssumeAllAuthCertsAreReal {
2373 n_authorities: usize,
2377 },
2378}
2379
2380pub fn consensus_threshold(n_authorities: usize) -> std::ops::RangeFrom<usize> {
2410 (n_authorities / 2) + 1 ..
2412}
2413
2414impl SignatureGroup {
2415 fn list_missing(&self, certs: &[AuthCert]) -> (usize, Vec<&Signature>) {
2422 let mut ok: HashSet<RsaIdentity> = HashSet::new();
2423 let mut missing = Vec::new();
2424 for sig in &self.signatures {
2425 let id_fingerprint = &sig.key_ids.id_fingerprint;
2426 if ok.contains(id_fingerprint) {
2427 continue;
2428 }
2429 if sig.find_cert(certs).is_some() {
2430 ok.insert(*id_fingerprint);
2431 continue;
2432 }
2433
2434 missing.push(sig);
2435 }
2436 (ok.len(), missing)
2437 }
2438
2439 fn could_validate(&self, authorities: &[&RsaIdentity]) -> bool {
2443 let mut signed_by: HashSet<RsaIdentity> = HashSet::new();
2444 for sig in &self.signatures {
2445 let id_fp = &sig.key_ids.id_fingerprint;
2446 if signed_by.contains(id_fp) {
2447 continue;
2449 }
2450 if authorities.contains(&id_fp) {
2451 signed_by.insert(*id_fp);
2452 }
2453 }
2454
2455 consensus_threshold(authorities.len()).contains(&signed_by.len())
2456 }
2457
2458 fn validate(&self, n_authorities: usize, certs: &[AuthCert]) -> Result<(), VerifyFailed> {
2465 self.verify_general(
2468 VerifyGeneralTrustedAuthorities::HazardouslyAssumeAllAuthCertsAreReal { n_authorities },
2469 certs,
2470 |tv| tv.verify(),
2471 )
2472 }
2473
2474 fn verify_general<E>(
2503 &self,
2504 trusted_authorities: VerifyGeneralTrustedAuthorities,
2505 certs: &[AuthCert],
2506 do_verify: impl Fn(ConsensusSignatureToVerify) -> Result<SignatureVerifiedIfIntended, E>,
2507 ) -> Result<(), E>
2508 where
2509 ConsensusVerifiabilityError: Into<E>,
2510 {
2511 use VerifyGeneralTrustedAuthorities as TA;
2512
2513 let mut ok: HashSet<RsaIdentity> = HashSet::new();
2517 let mut missing = HashSet::new();
2518 let mut verify_failed = Ok(());
2519
2520 for sig in &self.signatures {
2521 let Signature {
2523 digest_algo,
2524 key_ids:
2525 AuthCertKeyIds {
2526 id_fingerprint,
2527 sk_fingerprint: _,
2530 },
2531 signature: _,
2533 } = sig;
2534
2535 match trusted_authorities {
2536 TA::TrustThese { trusted } | TA::AnyOneOfThese { trusted } => {
2537 if !trusted.contains(id_fingerprint) {
2538 continue;
2539 }
2540 }
2541 TA::HazardouslyAssumeAllAuthCertsAreReal { .. } => {
2542 }
2544 }
2545
2546 if ok.contains(id_fingerprint) {
2547 continue;
2550 }
2551
2552 let Some(d) = self.hashes.hash_slice_for_verification(digest_algo) else {
2553 continue;
2556 };
2557
2558 let Some(tv) = sig.signature_to_verify(d, certs) else {
2559 missing.insert(sig.key_ids);
2560 continue;
2561 };
2562 match do_verify(tv) {
2563 Ok::<SignatureVerifiedIfIntended, _>(_) => {
2564 ok.insert(*id_fingerprint);
2565 }
2566 Err(e) => {
2567 verify_failed = Err(e);
2568 }
2569 }
2570 }
2571
2572 let n_authorities = match trusted_authorities {
2573 TA::TrustThese { trusted } => trusted.len(),
2574 TA::HazardouslyAssumeAllAuthCertsAreReal { n_authorities: n } => n,
2575 TA::AnyOneOfThese { .. } => {
2576 1
2580 }
2581 };
2582 let threshold = consensus_threshold(n_authorities);
2583
2584 if threshold.contains(&ok.len()) {
2585 Ok(())
2586 } else {
2587 verify_failed?;
2589
2590 Err(if missing.is_empty() {
2592 ConsensusVerifiabilityError::InsufficientTrustedSigners
2593 } else {
2594 let deficit = threshold.start - ok.len();
2595 ConsensusVerifiabilityError::MissingAuthCerts { missing, deficit }
2596 }
2597 .into())
2598 }
2599 }
2600}
2601
2602impl From<ConsensusVerifiabilityError> for VerifyFailed {
2603 fn from(cve: ConsensusVerifiabilityError) -> VerifyFailed {
2604 use ConsensusVerifiabilityError as CVE;
2605 use VerifyFailed as VF;
2606 match cve {
2607 CVE::InsufficientTrustedSigners => VF::InsufficientTrustedSigners,
2608 CVE::MissingAuthCerts { .. } => VF::InsufficientTrustedSigners,
2609 }
2610 }
2611}
2612
2613impl From<ConsensusVerifyFailed> for VerifyFailed {
2614 fn from(cvf: ConsensusVerifyFailed) -> VerifyFailed {
2615 use ConsensusVerifyFailed as CVF;
2616 use VerifyFailed as VF;
2617 match cvf {
2618 CVF::CertificationInsufficient { .. } => VF::InsufficientTrustedSigners,
2619 CVF::InvalidSignature { .. } => VF::VerifyFailed,
2620 }
2621 }
2622}
2623
2624#[cfg(test)]
2625mod test {
2626 #![allow(clippy::bool_assert_comparison)]
2628 #![allow(clippy::clone_on_copy)]
2629 #![allow(clippy::dbg_macro)]
2630 #![allow(clippy::mixed_attributes_style)]
2631 #![allow(clippy::print_stderr)]
2632 #![allow(clippy::print_stdout)]
2633 #![allow(clippy::single_char_pattern)]
2634 #![allow(clippy::unwrap_used)]
2635 #![allow(clippy::unchecked_time_subtraction)]
2636 #![allow(clippy::useless_vec)]
2637 #![allow(clippy::needless_pass_by_value)]
2638 #![allow(clippy::string_slice)] use super::*;
2641 use crate::doc::authcert::AuthCertUnverified;
2642 use crate::encode::{NetdocEncodable, NetdocEncodableFields};
2643 use crate::parse2::{ParseInput, parse_netdoc, parse_netdoc_multiple};
2644 use crate::test_support::regsub;
2645 use anyhow::Context as _;
2646 use assert_matches::assert_matches;
2647 use hex_literal::hex;
2648 use humantime::parse_rfc3339;
2649 use std::fmt::Debug;
2650 use std::fs;
2651 use std::time::Duration;
2652 use tor_checkable::TimeBound;
2653
2654 const CERTS: &str = include_str!("../../testdata/authcerts2.txt");
2655 const CONSENSUS: &str = include_str!("../../testdata/mdconsensus1.txt");
2656
2657 const PLAIN_CERTS: &str = include_str!("../../testdata2/cached-certs");
2658 const PLAIN_CONSENSUS: &str = include_str!("../../testdata2/cached-consensus");
2659
2660 fn read_bad(fname: &str) -> String {
2661 use std::fs;
2662 use std::path::PathBuf;
2663 let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
2664 path.push("testdata");
2665 path.push("bad-mdconsensus");
2666 path.push(fname);
2667
2668 fs::read_to_string(path).unwrap()
2669 }
2670
2671 #[test]
2672 fn parse_and_validate_md() -> crate::Result<()> {
2673 use std::net::SocketAddr;
2674 use tor_checkable::{SelfSigned, TimeBound};
2675 let mut certs = Vec::new();
2676 for cert in AuthCert::parse_multiple(CERTS)? {
2677 let cert = cert?.check_signature()?.dangerously_assume_timely();
2678 certs.push(cert);
2679 }
2680 let auth_ids: Vec<_> = certs.iter().map(|c| c.id_fingerprint()).collect();
2681
2682 assert_eq!(certs.len(), 3);
2683
2684 let (_, _, consensus) = MdConsensus::parse(CONSENSUS)?;
2685 let consensus = consensus.dangerously_assume_timely().set_n_authorities(3);
2686
2687 assert!(consensus.authorities_are_correct(&auth_ids));
2689 assert!(consensus.authorities_are_correct(&auth_ids[0..1]));
2691 {
2692 let bad_auth_id = (*b"xxxxxxxxxxxxxxxxxxxx").into();
2695 assert!(!consensus.authorities_are_correct(&[&bad_auth_id]));
2696 }
2697
2698 let missing = consensus.key_is_correct(&[]).err().unwrap();
2699 assert_eq!(3, missing.len());
2700 assert!(consensus.key_is_correct(&certs).is_ok());
2701 let missing = consensus.key_is_correct(&certs[0..1]).err().unwrap();
2702 assert_eq!(2, missing.len());
2703
2704 let same_three_times = vec![certs[0].clone(), certs[0].clone(), certs[0].clone()];
2706 let missing = consensus.key_is_correct(&same_three_times).err().unwrap();
2707
2708 assert_eq!(2, missing.len());
2709 assert!(consensus.is_well_signed(&same_three_times).is_err());
2710
2711 assert!(consensus.key_is_correct(&certs).is_ok());
2712 let consensus = consensus.check_signature(&certs)?;
2713
2714 assert_eq!(6, consensus.relays().len());
2715 let r0 = &consensus.relays()[0];
2716 assert_eq!(
2717 r0.md_digest(),
2718 &hex!("73dabe0a0468f4f7a67810a18d11e36731bb1d2ec3634db459100609f3b3f535")
2719 );
2720 assert_eq!(
2721 r0.rsa_identity().as_bytes(),
2722 &hex!("0a3057af2910415794d8ea430309d9ac5f5d524b")
2723 );
2724 assert!(!r0.weight().is_measured());
2725 assert!(!r0.weight().is_nonzero());
2726 let pv = &r0.protovers();
2727 assert!(pv.supports_subver("HSDir", 2));
2728 assert!(!pv.supports_subver("HSDir", 3));
2729 let ip4 = "127.0.0.1:5002".parse::<SocketAddr>().unwrap();
2730 let ip6 = "[::1]:5002".parse::<SocketAddr>().unwrap();
2731 assert!(r0.addrs().any(|a| a == ip4));
2732 assert!(r0.addrs().any(|a| a == ip6));
2733
2734 Ok(())
2735 }
2736
2737 #[test]
2738 fn parse_and_validate_ns() -> crate::Result<()> {
2739 use tor_checkable::{SelfSigned, TimeBound};
2740 let mut certs = Vec::new();
2741 for cert in AuthCert::parse_multiple(PLAIN_CERTS)? {
2742 let cert = cert?.check_signature()?.dangerously_assume_timely();
2743 certs.push(cert);
2744 }
2745 let auth_ids: Vec<_> = certs.iter().map(|c| c.id_fingerprint()).collect();
2746 assert_eq!(certs.len(), 4);
2747
2748 let (_, _, consensus) = PlainConsensus::parse(PLAIN_CONSENSUS)?;
2749 let consensus = consensus.dangerously_assume_timely().set_n_authorities(3);
2750 assert!(consensus.authorities_are_correct(&auth_ids));
2752 assert!(consensus.authorities_are_correct(&auth_ids[0..1]));
2754
2755 assert!(consensus.key_is_correct(&certs).is_ok());
2756
2757 let _consensus = consensus.check_signature(&certs)?;
2758
2759 Ok(())
2760 }
2761
2762 #[test]
2763 fn test_bad() {
2764 use crate::Pos;
2765 fn check(fname: &str, e: &Error) {
2766 let content = read_bad(fname);
2767 let res = MdConsensus::parse(&content);
2768 assert!(res.is_err());
2769 assert_eq!(&res.err().unwrap(), e);
2770 }
2771
2772 check(
2773 "bad-flags",
2774 &EK::BadArgument
2775 .at_pos(Pos::from_line(27, 1))
2776 .with_msg("Flags out of order"),
2777 );
2778 check(
2779 "bad-md-digest",
2780 &EK::BadArgument
2781 .at_pos(Pos::from_line(40, 3))
2782 .with_msg("Invalid base64"),
2783 );
2784 check(
2785 "bad-weight",
2786 &EK::BadArgument
2787 .at_pos(Pos::from_line(67, 141))
2788 .with_msg("invalid digit found in string"),
2789 );
2790 check(
2791 "bad-weights",
2792 &EK::BadArgument
2793 .at_pos(Pos::from_line(51, 13))
2794 .with_msg("invalid digit found in string"),
2795 );
2796 check(
2797 "wrong-order",
2798 &EK::WrongSortOrder.at_pos(Pos::from_line(52, 1)),
2799 );
2800 check(
2801 "wrong-start",
2802 &EK::UnexpectedToken
2803 .with_msg("vote-status")
2804 .at_pos(Pos::from_line(1, 1)),
2805 );
2806 check("wrong-version", &EK::BadDocumentVersion.with_msg("10"));
2807 }
2808
2809 fn gettok(s: &str) -> crate::Result<Item<'_, NetstatusKwd>> {
2810 let mut reader = NetDocReader::new(s)?;
2811 let tok = reader.next().unwrap();
2812 assert!(reader.next().is_none());
2813 tok
2814 }
2815
2816 #[test]
2817 fn test_weight() {
2818 let w = gettok("w Unmeasured=1 Bandwidth=6\n").unwrap();
2819 let w = RelayWeightsItem::from_item(&w).unwrap();
2820 assert!(!w.effective.is_measured());
2821 assert!(w.effective.is_nonzero());
2822
2823 let w = gettok("w Bandwidth=10\n").unwrap();
2824 let w = RelayWeightsItem::from_item(&w).unwrap();
2825 assert!(w.effective.is_measured());
2826 assert!(w.effective.is_nonzero());
2827
2828 let w = RelayWeightsItem::new_no_info();
2829 assert!(!w.effective.is_measured());
2830 assert!(!w.effective.is_nonzero());
2831
2832 let w = gettok("w Mustelid=66 Cheato=7 Unmeasured=1\n").unwrap();
2833 let w = RelayWeightsItem::from_item(&w).unwrap();
2834 assert!(!w.effective.is_measured());
2835 assert!(!w.effective.is_nonzero());
2836
2837 let w = gettok("r foo\n").unwrap();
2838 let w = RelayWeightsItem::from_item(&w);
2839 assert!(w.is_err());
2840
2841 let w = gettok("r Bandwidth=6 Unmeasured=Frog\n").unwrap();
2842 let w = RelayWeightsItem::from_item(&w);
2843 assert!(w.is_err());
2844
2845 let w = gettok("r Bandwidth=6 Unmeasured=3\n").unwrap();
2846 let w = RelayWeightsItem::from_item(&w);
2847 assert!(w.is_err());
2848 }
2849
2850 #[test]
2851 fn test_netparam() {
2852 let p = "Hello=600 Goodbye=5 Fred=7"
2853 .parse::<NetParams<u32>>()
2854 .unwrap();
2855 assert_eq!(p.get("Hello"), Some(&600_u32));
2856
2857 let p = "Hello=Goodbye=5 Fred=7".parse::<NetParams<u32>>();
2858 assert!(p.is_err());
2859
2860 let p = "Hello=Goodbye Fred=7".parse::<NetParams<u32>>();
2861 assert!(p.is_err());
2862
2863 for bad_kw in ["What=The", "", "\n", "\0"] {
2864 let p = [(bad_kw, 42)].into_iter().collect::<NetParams<i32>>();
2865 let mut d = NetdocEncoder::new();
2866 let d = (|| {
2867 let i = d.item("bad-psrams");
2868 p.write_item_value_onto(i)?;
2869 d.finish()
2870 })();
2871 let _: tor_error::Bug = d.expect_err(bad_kw);
2872 }
2873 }
2874
2875 #[test]
2876 fn test_sharedrand() {
2877 let sr =
2878 gettok("shared-rand-previous-value 9 5LodY4yWxFhTKtxpV9wAgNA9N8flhUCH0NqQv1/05y4\n")
2879 .unwrap();
2880 let sr = SharedRandStatus::from_item(&sr).unwrap();
2881
2882 assert_eq!(sr.n_reveals, 9);
2883 assert_eq!(
2884 sr.value.0,
2885 hex!("e4ba1d638c96c458532adc6957dc0080d03d37c7e5854087d0da90bf5ff4e72e")
2886 );
2887 assert!(sr.timestamp.is_none());
2888
2889 let sr2 = gettok(
2890 "shared-rand-current-value 9 \
2891 5LodY4yWxFhTKtxpV9wAgNA9N8flhUCH0NqQv1/05y4 2022-01-20T12:34:56\n",
2892 )
2893 .unwrap();
2894 let sr2 = SharedRandStatus::from_item(&sr2).unwrap();
2895 assert_eq!(sr2.n_reveals, sr.n_reveals);
2896 assert_eq!(sr2.value.0, sr.value.0);
2897 assert_eq!(
2898 sr2.timestamp.unwrap().0,
2899 humantime::parse_rfc3339("2022-01-20T12:34:56Z").unwrap()
2900 );
2901
2902 let sr = gettok("foo bar\n").unwrap();
2903 let sr = SharedRandStatus::from_item(&sr);
2904 assert!(sr.is_err());
2905 }
2906
2907 #[test]
2908 fn test_protostatus() {
2909 let my_protocols: Protocols = "Link=7 Cons=1-5 Desc=3-10".parse().unwrap();
2910
2911 let outcome = ProtoStatus {
2912 recommended: "Link=7".parse().unwrap(),
2913 required: "Desc=5".parse().unwrap(),
2914 __non_exhaustive: (),
2915 }
2916 .check_protocols(&my_protocols);
2917 assert!(outcome.is_ok());
2918
2919 let outcome = ProtoStatus {
2920 recommended: "Microdesc=4 Link=7".parse().unwrap(),
2921 required: "Desc=5".parse().unwrap(),
2922 __non_exhaustive: (),
2923 }
2924 .check_protocols(&my_protocols);
2925 assert_eq!(
2926 outcome,
2927 Err(ProtocolSupportError::MissingRecommended(
2928 "Microdesc=4".parse().unwrap()
2929 ))
2930 );
2931
2932 let outcome = ProtoStatus {
2933 recommended: "Microdesc=4 Link=7".parse().unwrap(),
2934 required: "Desc=5 Cons=5-12 Wombat=15".parse().unwrap(),
2935 __non_exhaustive: (),
2936 }
2937 .check_protocols(&my_protocols);
2938 assert_eq!(
2939 outcome,
2940 Err(ProtocolSupportError::MissingRequired(
2941 "Cons=6-12 Wombat=15".parse().unwrap()
2942 ))
2943 );
2944 }
2945
2946 #[test]
2947 fn serialize_protostatus() {
2948 let ps = ProtoStatuses {
2949 client: ProtoStatus {
2950 recommended: "Link=1-5 LinkAuth=2-5".parse().unwrap(),
2951 required: "Link=5 LinkAuth=3".parse().unwrap(),
2952 __non_exhaustive: (),
2953 },
2954 relay: ProtoStatus {
2955 recommended: "Wombat=20-30 Knish=20-30".parse().unwrap(),
2956 required: "Wombat=20-22 Knish=25-27".parse().unwrap(),
2957 __non_exhaustive: (),
2958 },
2959 __non_exhaustive: (),
2960 };
2961 let json = serde_json::to_string(&ps).unwrap();
2962 let ps2 = serde_json::from_str(json.as_str()).unwrap();
2963 assert_eq!(ps, ps2);
2964
2965 let ps3: ProtoStatuses = serde_json::from_str(
2966 r#"{
2967 "client":{
2968 "required":"Link=5 LinkAuth=3",
2969 "recommended":"Link=1-5 LinkAuth=2-5"
2970 },
2971 "relay":{
2972 "required":"Wombat=20-22 Knish=25-27",
2973 "recommended":"Wombat=20-30 Knish=20-30"
2974 }
2975 }"#,
2976 )
2977 .unwrap();
2978 assert_eq!(ps, ps3);
2979 }
2980
2981 #[test]
2983 fn verify_error_netstatus_vote() -> Result<(), anyhow::Error> {
2984 use VerifyFailed as VF;
2985 use VoteVerifyFailed as VVF;
2986 use vote::NetworkStatusUnverified as UV;
2987
2988 let file = "testdata2/v3-status-votes--1";
2989 let text = fs::read_to_string(file).with_context(|| file.to_owned())?;
2990 let input = ParseInput::new(&text, file);
2991 let doc: UV = parse_netdoc(&input)?;
2992 let trusted = [doc.peek_alleged_authority()];
2993
2994 let edit_body = |f: &dyn Fn(&mut _)| {
2995 let (mut body, sigs) = doc.clone().unwrap_unverified();
2996 f(&mut body);
2997 UV::from_parts(body, sigs)
2998 };
2999
3000 {
3002 let mut doc = doc.clone();
3003 doc.sigs.sigs.directory_signature.signature.fill(0xff);
3004 assert_matches!(
3005 doc.verify(&trusted),
3006 Err(VVF::InvalidSignature(VF::VerifyFailed))
3007 );
3008 }
3009
3010 {
3012 let doc = doc.clone();
3013 assert_matches!(
3014 doc.verify(&[[0x55; _].into()]),
3015 Err(VVF::InvalidSignature(VF::InsufficientTrustedSigners))
3016 );
3017 }
3018
3019 {
3021 let doc = edit_body(&|body| {
3022 body.authority.authority.dir_source.identity.0 = [0x55; _].into();
3023 });
3024 assert_matches!(
3025 doc.verify(&trusted),
3027 Err(VVF::AuthCertWrongAuthority)
3028 );
3029 }
3030
3031 let with_mutated_lifetime = |f: &dyn Fn(&mut Lifetime)| {
3033 let doc = edit_body(&|body| f(&mut body.preamble.lifetime));
3034 assert_matches!(
3035 doc.verify(&trusted),
3037 Err(VVF::AuthCertWrongValidity(_))
3038 );
3039 };
3040 let t_past = parse_rfc3339("1990-01-01T00:02:25Z")?;
3041 let t_future = parse_rfc3339("2010-01-01T00:02:25Z")?;
3042 with_mutated_lifetime(&|lifetime| lifetime.valid_after.0 = t_future);
3043 with_mutated_lifetime(&|lifetime| lifetime.fresh_until.0 = t_past);
3044 with_mutated_lifetime(&|lifetime| lifetime.valid_until.0 = t_past);
3045
3046 {
3048 let mut text = text.clone();
3049 regsub(&mut text, "^dir-key-expires ", "dir-key-expires-SABOTAGED ");
3050 let input = ParseInput::new(&text, file);
3051 let doc: UV = parse_netdoc(&input)?;
3052 assert_matches!(
3053 doc.verify(&trusted),
3055 Err(VVF::AuthCertParseError(..))
3056 );
3057 }
3058
3059 Ok(())
3060 }
3061
3062 #[cfg(feature = "retain-unknown")]
3063 #[allow(clippy::type_complexity)]
3064 pub(super) fn prep_netstatus_verify<UV: NetdocParseable>(
3065 file: &str,
3066 ) -> anyhow::Result<(UV, String, Vec<AuthCert>, Vec<RsaIdentity>, SystemTime)> {
3067 let text = fs::read_to_string(file).with_context(|| file.to_owned())?;
3068 let now = parse_rfc3339("2000-01-01T00:02:25Z")?;
3069
3070 let mut input = ParseInput::new(&text, file);
3071 input.retain_unknown_values();
3072
3073 let doc: UV = parse_netdoc(&input)?;
3074
3075 let certs = {
3076 let file = "testdata2/cached-certs";
3077 let text = fs::read_to_string(file)?;
3078 let input = ParseInput::new(&text, file);
3079 let certs: Vec<AuthCertUnverified> = parse_netdoc_multiple(&input)?;
3080 certs
3081 .into_iter()
3082 .map(|cert| cert.verify_selfcert(now))
3083 .collect::<Result<Vec<AuthCert>, _>>()?
3084 };
3085
3086 let authorities = certs.iter().map(|cert| *cert.fingerprint).collect_vec();
3087
3088 Ok((doc, text, certs, authorities, now))
3089 }
3090
3091 #[cfg(feature = "retain-unknown")]
3104 fn roundtrip_netstatus<UV, V, VE>(
3105 file: &str,
3108 verify: impl FnOnce(UV, &[RsaIdentity], &[AuthCert]) -> Result<TimeRangeBound<V>, VE>,
3109 adjust_now: Duration,
3110 ) -> anyhow::Result<()>
3111 where
3112 UV: NetdocParseable + NetdocParseableUnverified + MungeForRoundtrip,
3113 UV::Signatures: Clone + Debug + NetdocEncodableFields,
3114 VE: Debug + std::error::Error + Send + Sync + 'static,
3115 V: Debug + NetdocEncodable,
3116 {
3117 let (doc, text, certs, authorities, now) = prep_netstatus_verify::<UV>(file)?;
3118
3119 let now = now + adjust_now;
3120
3121 let sigs = doc.inspect_unverified().1.sigs.clone();
3122
3123 let doc = verify(doc, &authorities, &certs)?.if_valid_at(&now)?;
3124
3125 println!("{doc:#?}");
3126
3127 let mut enc = NetdocEncoder::new();
3128 doc.encode_unsigned(&mut enc)?;
3129 sigs.encode_fields(&mut enc)?;
3130 let enc = enc.finish()?;
3131
3132 let mut exp: String = text.clone();
3133
3134 regsub(
3136 &mut exp,
3138 r#"^(shared-rand-.*)$"#,
3139 |c: ®ex::Captures| {
3140 let mut s = c[1].to_owned();
3141 regsub(&mut s, r#"="#, "");
3142 s
3143 },
3144 );
3145
3146 regsub(
3149 &mut exp,
3151 r#"^(client|server)-versions (.+)$"#,
3152 |c: ®ex::Captures| -> String {
3153 format!(
3154 "{}-versions {}",
3155 &c[1],
3156 iter_join(",", c[2].split(',').sorted()),
3157 )
3158 },
3159 );
3160
3161 let mut regsub = |re, repl| regsub(&mut exp, re, repl);
3162
3163 regsub(
3165 r#"^((?:client|server)-versions) $"#,
3167 "$1",
3168 );
3169
3170 regsub(
3174 r#"(?x)
3175 ( ^ r\ .* \n ) # ( r ) $1, part before where we want to put m's
3176 ( (?: .* \n )*? ) # (.*? ) $2, the rest, before the m's
3177 ( (?: m\ .* \n )+ ) # ( m+ ) $3, one or more m's
3178 "#,
3179 r#"$1$3$2"#,
3180 );
3181
3182 UV::adjust_exp(&mut exp);
3183
3184 assert_eq_or_diff!(&exp, &enc);
3185
3186 Ok(())
3187 }
3188
3189 trait MungeForRoundtrip {
3190 fn adjust_exp(exp: &mut String);
3192 }
3193
3194 #[cfg(feature = "retain-unknown")]
3198 #[test]
3199 fn roundtrip_netstatus_plain() -> anyhow::Result<()> {
3200 roundtrip_netstatus::<plain::NetworkStatusUnverified, _, _>(
3201 "testdata2/cached-consensus",
3202 plain::NetworkStatusUnverified::verify,
3203 Duration::ZERO,
3204 )
3205 }
3206
3207 impl MungeForRoundtrip for plain::NetworkStatusUnverified {
3208 fn adjust_exp(exp: &mut String) {
3209 let mut regsub = |re, repl| regsub(exp, re, repl);
3210
3211 regsub(
3214 r#"^network-status-version 3$"#,
3215 "network-status-version 3 ns",
3216 );
3217
3218 regsub(
3222 r#"^(r \S+ \S+ \S+) \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"#,
3223 "$1 2000-01-01 00:00:01",
3224 );
3225 }
3226 }
3227
3228 #[cfg(feature = "retain-unknown")]
3229 #[test]
3230 fn roundtrip_netstatus_md() -> anyhow::Result<()> {
3231 roundtrip_netstatus::<md::NetworkStatusUnverified, _, _>(
3232 "testdata2/cached-microdesc-consensus",
3233 md::NetworkStatusUnverified::verify,
3234 Duration::ZERO,
3235 )
3236 }
3237
3238 impl MungeForRoundtrip for md::NetworkStatusUnverified {
3239 fn adjust_exp(exp: &mut String) {
3240 let mut regsub = |re, repl| regsub(exp, re, repl);
3241
3242 regsub(
3248 r#"^(r \S+ \S+) \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"#,
3249 "$1 2000-01-01 00:00:01",
3250 );
3251 }
3252 }
3253
3254 #[cfg(feature = "retain-unknown")]
3255 #[test]
3256 fn roundtrip_netstatus_vote() -> anyhow::Result<()> {
3257 roundtrip_netstatus::<vote::NetworkStatusUnverified, _, _>(
3258 "testdata2/v3-status-votes--1",
3259 |doc, trusted, _| vote::NetworkStatusUnverified::verify(doc, trusted),
3260 Duration::from_secs(20),
3261 )
3262 }
3263
3264 impl MungeForRoundtrip for vote::NetworkStatusUnverified {
3265 fn adjust_exp(exp: &mut String) {
3266 let stats_massage_entry = |e: &str| {
3270 let mut e = e.to_owned();
3271 if e.contains('.') {
3272 regsub(
3273 &mut e,
3274 r#"(?x)^ ( (?:wfu) = [0-9.]*? )( \.? 0+ ) $"#,
3276 "$1",
3277 );
3278 }
3279 e
3280 };
3281
3282 regsub(exp, r#"^stats (.+)$"#, |c: ®ex::Captures| -> String {
3284 format!(
3285 "stats {}",
3286 iter_join(" ", c[1].split(' ').sorted().map(stats_massage_entry)),
3287 )
3288 });
3289
3290 let mut regsub = |re: &_, repl| regsub(exp, re, repl);
3291
3292 regsub(
3294 r#"(?x)
3295 ^ (recommended-relay-protocols\ .*) \n
3296 (recommended-client-protocols\ .*) \n
3297 (required-relay-protocols\ .*) \n
3298 (required-client-protocols\ .*) \n
3299 (known-flags .*)$ \n
3300 "#,
3301 r#"$5
3302$2
3303$1
3304$4
3305$3
3306"#,
3307 );
3308
3309 regsub(
3315 r#"(?x) ^ (voting-delay\ .*) \n
3316 (known-flags\ .*) \n"#,
3317 "$1
3318client-versions
3319server-versions
3320$2
3321",
3322 );
3323
3324 for missing_field in [
3327 "bandwidth-file-headers", "bandwidth-file-digest", "flag-thresholds", ] {
3331 regsub(&format!(r#"^{missing_field} .*\n"#), "");
3332 }
3333 }
3334 }
3335
3336 fn testdata_live(f: &str) -> String {
3337 let var = "TOR_NETDOC_TESTDATA_LIVE_PREFIX";
3341 let prefix = std::env::var_os(var)
3342 .map(|s| s.into_string().expect(var))
3343 .unwrap_or_else(|| "testdata-live/".into());
3344 format!("{prefix}{f}")
3345 }
3346
3347 #[allow(clippy::unnecessary_wraps)] fn unwrap_unverified_for_test<UV: NetdocParseableUnverified>(
3349 uv: UV,
3350 _ids: &[RsaIdentity],
3351 _certs: &[AuthCert],
3352 ) -> Result<TimeRangeBound<UV::Body>, std::convert::Infallible> {
3353 Ok(TimeRangeBound::new(uv.unwrap_unverified().0, ..))
3354 }
3355
3356 #[cfg(feature = "retain-unknown")]
3357 #[test]
3358 fn roundtrip_live_plain() -> anyhow::Result<()> {
3359 roundtrip_netstatus::<plain::NetworkStatusUnverified, _, _>(
3360 &testdata_live("consensus"),
3361 unwrap_unverified_for_test,
3362 Duration::ZERO,
3363 )
3364 }
3365
3366 #[cfg(feature = "retain-unknown")]
3367 #[test]
3368 fn roundtrip_live_md() -> anyhow::Result<()> {
3369 roundtrip_netstatus::<md::NetworkStatusUnverified, _, _>(
3370 &testdata_live("consensus-microdesc"),
3371 unwrap_unverified_for_test,
3372 Duration::ZERO,
3373 )
3374 }
3375
3376 #[cfg(feature = "retain-unknown")]
3377 #[test]
3378 fn roundtrip_live_vote() -> anyhow::Result<()> {
3379 roundtrip_netstatus::<vote::NetworkStatusUnverified, _, _>(
3380 &testdata_live("authority"),
3381 unwrap_unverified_for_test,
3382 Duration::ZERO,
3383 )
3384 }
3385}