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::{ConsensusAuthoritySection, DirSource, SupersededAuthorityKey};
130
131define_constant_string! {
132 NetworkStatusVersion = "3";
142}
143
144define_constant_string! {
145 VoteStatusConsensus = "consensus";
149}
150
151define_constant_string! {
152 VoteStatusVote = "vote";
156}
157
158#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Default)]
172#[allow(clippy::exhaustive_structs)]
173pub struct IgnoredPublicationTimeSp;
174
175#[derive(Clone, Debug, PartialEq, Eq, Deftly)]
183#[derive_deftly(Constructor, NetdocEncodableFields, NetdocParseableFields)]
184#[derive_deftly(Lifetime)]
185#[allow(clippy::exhaustive_structs)]
186pub struct Lifetime {
187 #[deftly(constructor)]
194 #[deftly(netdoc(single_arg))]
195 pub valid_after: Iso8601TimeSp,
196 #[deftly(constructor)]
204 #[deftly(netdoc(single_arg))]
205 pub fresh_until: Iso8601TimeSp,
206 #[deftly(constructor)]
214 #[deftly(netdoc(single_arg))]
215 pub valid_until: Iso8601TimeSp,
216
217 #[doc(hidden)]
218 #[deftly(netdoc(skip))]
219 pub __non_exhaustive: (),
220}
221
222define_derive_deftly! {
223 Lifetime:
225
226 ${defcond FIELD not(approx_equal($fname, __non_exhaustive))}
227
228 impl Lifetime {
229 pub fn new(
231 $( ${when FIELD} $fname: time::SystemTime, )
232 ) -> crate::Result<Self> {
233 let self_ = Lifetime {
237 $( ${when FIELD} $fname: $fname.into(), )
238 __non_exhaustive: (),
239 };
240 if self_.valid_after < self_.fresh_until && self_.fresh_until < self_.valid_until {
241 Ok(self_)
242 } else {
243 Err(EK::InvalidLifetime.err())
244 }
245 }
246 $(
247 ${when FIELD}
248
249 ${fattrs doc}
250 pub fn $fname(&self) -> time::SystemTime {
251 *self.$fname
252 }
253 )
254 pub fn valid_at(&self, when: time::SystemTime) -> bool {
256 *self.valid_after <= when && when <= *self.valid_until
257 }
258
259 pub fn voting_period(&self) -> time::Duration {
264 let valid_after = self.valid_after();
265 let fresh_until = self.fresh_until();
266 fresh_until
267 .duration_since(valid_after)
268 .expect("Mis-formed lifetime")
269 }
270 }
271}
272use derive_deftly_template_Lifetime;
273
274#[derive(Debug, Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Copy)] #[derive(derive_more::From, derive_more::Into, derive_more::Display, derive_more::FromStr)]
286#[allow(clippy::exhaustive_structs)] pub struct ConsensusMethod(pub u32);
288impl NormalItemArgument for ConsensusMethod {}
289
290#[derive(Debug, Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Deftly)]
297#[derive_deftly(ItemValueEncodable, ItemValueParseable)]
298#[non_exhaustive]
299pub struct ConsensusMethods {
300 pub methods: BTreeSet<ConsensusMethod>,
302}
303
304pub mod consensus_methods_comma_separated {
309 use super::*;
310 use parse2::ArgumentError as AE;
311 use std::result::Result;
312
313 pub fn from_args<'s>(args: &mut ArgumentStream<'s>) -> Result<ConsensusMethods, AE> {
315 let mut methods = BTreeSet::new();
316 for ent in args.next().ok_or(AE::Missing)?.split(',') {
317 let ent = ent.parse().map_err(|_| AE::Invalid)?;
318 if !methods.insert(ent) {
319 return Err(AE::Invalid);
320 }
321 }
322 Ok(ConsensusMethods { methods })
323 }
324
325 pub fn write_arg_onto(self_: &ConsensusMethods, out: &mut ItemEncoder) -> Result<(), Bug> {
327 out.args_raw_string(&iter_join(",", &self_.methods));
328 Ok(())
329 }
330}
331
332#[derive(Debug, Clone, Educe, Eq, PartialEq)]
358#[educe(Default)]
359pub struct NetParams<T> {
360 params: HashMap<String, T>,
362}
363
364impl<T> NetParams<T> {
365 #[allow(unused)]
367 pub fn new() -> Self {
368 NetParams {
369 params: HashMap::new(),
370 }
371 }
372 pub fn get<A: AsRef<str>>(&self, v: A) -> Option<&T> {
374 self.params.get(v.as_ref())
375 }
376 pub fn iter(&self) -> impl Iterator<Item = (&String, &T)> {
378 self.params.iter()
379 }
380 pub fn set(&mut self, k: String, v: T) {
382 self.params.insert(k, v);
383 }
384}
385
386impl<K: Into<String>, T> FromIterator<(K, T)> for NetParams<T> {
387 fn from_iter<I: IntoIterator<Item = (K, T)>>(i: I) -> Self {
388 NetParams {
389 params: i.into_iter().map(|(k, v)| (k.into(), v)).collect(),
390 }
391 }
392}
393
394impl<T> std::iter::Extend<(String, T)> for NetParams<T> {
395 fn extend<I: IntoIterator<Item = (String, T)>>(&mut self, iter: I) {
396 self.params.extend(iter);
397 }
398}
399
400impl<'de, T> Deserialize<'de> for NetParams<T>
401where
402 T: Deserialize<'de>,
403{
404 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
405 where
406 D: Deserializer<'de>,
407 {
408 let params = HashMap::deserialize(deserializer)?;
409 Ok(NetParams { params })
410 }
411}
412
413#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
422pub struct ProtoStatus {
423 recommended: Protocols,
428 required: Protocols,
433}
434
435impl ProtoStatus {
436 pub fn check_protocols(
446 &self,
447 supported_protocols: &Protocols,
448 ) -> Result<(), ProtocolSupportError> {
449 let missing_required = self.required.difference(supported_protocols);
451 if !missing_required.is_empty() {
452 return Err(ProtocolSupportError::MissingRequired(missing_required));
453 }
454 let missing_recommended = self.recommended.difference(supported_protocols);
455 if !missing_recommended.is_empty() {
456 return Err(ProtocolSupportError::MissingRecommended(
457 missing_recommended,
458 ));
459 }
460
461 Ok(())
462 }
463}
464
465#[derive(Clone, Debug, thiserror::Error)]
467#[cfg_attr(test, derive(PartialEq))]
468#[non_exhaustive]
469pub enum ProtocolSupportError {
470 #[error("Required protocols are not implemented: {0}")]
472 MissingRequired(Protocols),
473
474 #[error("Recommended protocols are not implemented: {0}")]
478 MissingRecommended(Protocols),
479}
480
481impl ProtocolSupportError {
482 pub fn should_shutdown(&self) -> bool {
484 matches!(self, Self::MissingRequired(_))
485 }
486}
487
488impl HasKind for ProtocolSupportError {
489 fn kind(&self) -> tor_error::ErrorKind {
490 tor_error::ErrorKind::SoftwareDeprecated
491 }
492}
493
494#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
501pub struct ProtoStatuses {
502 client: ProtoStatus,
504 relay: ProtoStatus,
506}
507
508impl ProtoStatuses {
509 pub fn client(&self) -> &ProtoStatus {
511 &self.client
512 }
513
514 pub fn relay(&self) -> &ProtoStatus {
516 &self.relay
517 }
518}
519
520#[derive(Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd)] #[derive(derive_more::Deref, derive_more::Into)]
541pub struct RecommendedTorVersions(BTreeSet<String>);
542
543#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
545#[non_exhaustive]
546pub enum InvalidRecommendedTorVersions {
547 #[error("version {_0:?} contains whitespace")]
549 ContainsWhitespace(String),
550
551 #[error("version {_0:?} is repeated")]
553 Repeated(String),
554}
555
556impl RecommendedTorVersions {
557 pub fn new_unknown() -> Self {
559 Self::default()
560 }
561
562 pub fn is_known(&self) -> bool {
568 !self.is_empty()
569 }
570
571 #[allow(clippy::should_implement_trait)] pub fn from_iter<I, S>(i: I) -> Result<Self, InvalidRecommendedTorVersions>
574 where
575 I: IntoIterator<Item = S>,
576 S: AsRef<str>,
577 {
578 let mut set = BTreeSet::new();
579 for v in i {
580 let v = v.as_ref();
581 if v.is_empty() {
582 continue;
583 }
584 if v.chars().any(|c| c.is_whitespace()) {
585 return Err(InvalidRecommendedTorVersions::ContainsWhitespace(
586 v.to_owned(),
587 ));
588 }
589 if !set.insert(v.to_owned()) {
590 return Err(InvalidRecommendedTorVersions::Repeated(v.to_owned()));
591 }
592 }
593 Ok(RecommendedTorVersions(set))
594 }
595}
596
597impl FromStr for RecommendedTorVersions {
598 type Err = InvalidRecommendedTorVersions;
599 fn from_str(s: &str) -> Result<Self, InvalidRecommendedTorVersions> {
600 Self::from_iter(s.split(','))
601 }
602}
603
604impl Display for RecommendedTorVersions {
605 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
606 write!(f, "{}", iter_join(",", &self.0))
607 }
608}
609
610impl NormalItemArgument for RecommendedTorVersions {}
611
612impl ItemValueEncodable for RecommendedTorVersions {
613 fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
614 out.args_raw_string(self);
615 Ok(())
616 }
617}
618
619impl ItemValueParseable for RecommendedTorVersions {
620 fn from_unparsed(mut item: UnparsedItem) -> Result<Self, ErrorProblem> {
621 const FIELD: &str = "versions";
622 item.check_no_object()?;
623 let args = item.args_mut();
624 let arg = args.next().unwrap_or("");
625 arg.parse::<Self>()
626 .map_err(|_| args.handle_error(FIELD, ArgumentError::Invalid))
627 }
628}
629
630#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
638#[allow(clippy::exhaustive_enums)]
639pub enum ConsensusFlavor {
640 Microdesc,
643 Plain,
648}
649
650impl ConsensusFlavor {
651 pub fn name(&self) -> &'static str {
653 match self {
654 ConsensusFlavor::Plain => "ns", ConsensusFlavor::Microdesc => "microdesc",
656 }
657 }
658 pub fn from_opt_name(name: Option<&str>) -> crate::Result<Self> {
663 match name {
664 Some("microdesc") => Ok(ConsensusFlavor::Microdesc),
665 Some("ns") | None => Ok(ConsensusFlavor::Plain),
666 Some(other) => {
667 Err(EK::BadDocumentType.with_msg(format!("unrecognized flavor {:?}", other)))
668 }
669 }
670 }
671}
672
673define_derive_deftly! {
674 DirectorySignaturesHashesAccu:
682
683 ${define FNAME ${paste ${snake_case $vname}} }
684
685 #[derive(Clone, Copy, Default, Debug, Eq, PartialEq, Deftly)]
687 #[derive_deftly(AsMutSelf)]
688 #[non_exhaustive]
689 pub struct DirectorySignaturesHashesAccu {
690 $(
691 ${vattrs doc}
692 pub $FNAME: Option<[u8; ${vmeta(hash_len) as expr}]>,
693 )
694
695 pub sha1_unnamed: Option<[u8; 20]>,
705 }
706
707 impl DirectorySignaturesHashesAccu {
708 fn update_from(
710 &mut self,
711 algo: &DigestAlgoInSignature,
712 body: &SignatureHashInputs,
713 ) {
714 ${define HASH {
717 self.$UPDATE.get_or_insert_with(|| {
719 let mut h = tor_llcrypto::d::$ALGO::new();
720 h.update(body.body().body());
721 h.update(body.signature_item_kw_spc);
722 h.finalize().into()
723 });
724 }}
725
726 match &**algo {
727 $(
728 Some(KeywordOrString::Known($vtype)) => {
729 ${define UPDATE $FNAME}
730 ${define ALGO $vname}
731 $HASH
732 }
733 )
734 None => {
735 ${define UPDATE sha1_unnamed}
736 ${define ALGO Sha1}
737 $HASH
738 }
739 Some(KeywordOrString::Unknown(..)) => {}
740 }
741 }
742
743 fn hash_slice_for_verification(
748 &self,
749 algo: &DigestAlgoInSignature,
750 ) -> Option<&[u8]> {
751 match &**algo {
752 $(
753 Some(KeywordOrString::Known($vtype)) => Some(self.$FNAME.as_ref()?),
754 )
755 None => Some(self.sha1_unnamed.as_ref()?),
756 Some(KeywordOrString::Unknown(..)) => None,
757 }
758 }
759 }
760}
761
762#[derive(Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, Deftly)]
764#[derive_deftly(DirectorySignaturesHashesAccu)]
765#[non_exhaustive]
766#[strum(serialize_all = "snake_case")]
767pub enum DirectorySignatureHashAlgo {
768 #[deftly(hash_len = "20")]
770 Sha1,
771 #[deftly(hash_len = "32")]
773 Sha256,
774}
775
776#[derive(Debug, Clone, derive_more::Deref, derive_more::DerefMut)]
788#[allow(clippy::exhaustive_structs)]
789pub struct DigestAlgoInSignature(pub Option<KeywordOrString<DirectorySignatureHashAlgo>>);
790
791impl ItemArgumentParseable for DigestAlgoInSignature {
792 fn from_args<'s>(args: &mut ArgumentStream<'s>) -> Result<Self, ArgumentError> {
793 let v = if args
794 .clone()
795 .next()
796 .and_then(|s| s.chars().all(|c| c.is_ascii_hexdigit()).then_some(()))
800 .is_some()
801 {
802 None
804 } else {
805 Some(KeywordOrString::from_args(args)?)
806 };
807 Ok(DigestAlgoInSignature(v))
808 }
809}
810impl ItemArgument for DigestAlgoInSignature {
811 fn write_arg_onto(&self, out: &mut ItemEncoder<'_>) -> Result<(), Bug> {
812 if let Some(y) = &self.0 {
813 y.write_arg_onto(out)?;
814 }
815 Ok(())
816 }
817}
818impl DigestAlgoInSignature {
819 pub fn algorithm(&self) -> &KeywordOrString<DirectorySignatureHashAlgo> {
823 self.as_ref()
824 .unwrap_or(&KeywordOrString::Known(DirectorySignatureHashAlgo::Sha1))
825 }
826}
827
828impl NormalItemArgument for DirectorySignatureHashAlgo {}
829
830#[derive(Debug, Clone, Deftly)]
835#[derive_deftly(ItemValueEncodable, ItemValueParseable)]
836#[non_exhaustive]
837pub struct Signature {
838 pub digest_algo: DigestAlgoInSignature,
843 #[deftly(netdoc(with = authcert::keyids_directory_signature_args))]
846 pub key_ids: AuthCertKeyIds,
847 #[deftly(netdoc(object(label = "SIGNATURE"), with = types::raw_data_object))]
849 pub signature: Vec<u8>,
850}
851
852impl SignatureItemParseable for Signature {
853 type HashAccu = DirectorySignaturesHashesAccu;
854
855 fn from_unparsed_and_body(
856 item: UnparsedItem,
857 body: &SignatureHashInputs<'_>,
858 hash: &mut Self::HashAccu,
859 ) -> Result<Self, ErrorProblem> {
860 let signature = Signature::from_unparsed(item)?;
861 hash.update_from(&signature.digest_algo, body);
862 Ok(signature)
863 }
864}
865
866#[derive(Debug, Clone)]
872#[non_exhaustive]
873pub struct SignatureGroup {
874 pub hashes: DirectorySignaturesHashesAccu,
880 pub signatures: Vec<Signature>,
882}
883
884#[derive(Clone, Debug, thiserror::Error)]
895#[allow(clippy::exhaustive_enums)]
896pub enum ConsensusVerifiabilityError {
897 #[error("consensus not signed by enough authorities")]
899 InsufficientTrustedSigners,
900
901 #[error("missing auth certs mean we could not verify enough consensuis signatures (need at least {deficit} more, out of {} that are missing)", missing.len())]
903 MissingAuthCerts {
904 deficit: usize,
906 missing: HashSet<AuthCertKeyIds>,
908 },
909}
910
911#[derive(Clone, Debug, thiserror::Error)]
923#[non_exhaustive]
924pub enum ConsensusVerifyFailed {
925 #[error("certs/sigs insufficient")]
927 CertificationInsufficient(#[from] ConsensusVerifiabilityError),
928
929 #[error("invalid signature")]
931 InvalidSignature(#[source] VerifyFailed),
936}
937
938#[derive(Clone, Debug, thiserror::Error)]
948#[non_exhaustive]
949pub enum VoteVerifyFailed {
950 #[error("invalid signature")]
952 InvalidSignature(#[source] VerifyFailed),
957
958 #[error("unparseable authcert")]
960 AuthCertParseError(#[source] parse2::ParseError),
961
962 #[error("authcert not valid for vote period")]
964 AuthCertWrongValidity(#[source] tor_checkable::TimeValidityError),
965
966 #[error("wrong authcert")]
968 AuthCertWrongAuthority,
969}
970
971#[derive(
973 Debug, Clone, Copy, Eq, PartialEq, derive_more::From, derive_more::Into, derive_more::AsRef,
974)]
975pub struct SharedRandVal([u8; 32]);
977
978#[derive(Debug, Clone, Deftly)]
981#[non_exhaustive]
982#[derive_deftly(ItemValueEncodable, ItemValueParseable)]
983pub struct SharedRandStatus {
984 pub n_reveals: u8,
986 pub value: SharedRandVal,
993
994 pub timestamp: Option<Iso8601TimeNoSp>,
998}
999
1000#[derive(Debug, Clone, Default, Deftly)]
1007#[derive_deftly(Constructor, NetdocEncodableFields, NetdocParseableFields)]
1008#[allow(clippy::exhaustive_structs)]
1009pub struct SharedRandStatuses {
1010 pub shared_rand_previous_value: Option<SharedRandStatus>,
1012
1013 pub shared_rand_current_value: Option<SharedRandStatus>,
1015
1016 #[doc(hidden)]
1017 #[deftly(netdoc(skip))]
1018 pub __non_exhaustive: (),
1019}
1020
1021#[derive(Debug, Clone)]
1078pub struct RelayWeightsItem {
1079 effective: RelayWeight,
1081
1082 params: Unknown<Option<NetParams<u32>>>,
1084}
1085
1086#[derive(Debug, Clone, Deftly)]
1088#[derive_deftly(NetdocEncodableFields, NetdocParseableFields)]
1089#[allow(clippy::exhaustive_structs)] pub struct VoteRelayWeightsItem {
1091 pub w: Option<NetParams<u32>>,
1093}
1094
1095#[non_exhaustive]
1099#[derive(Debug, Clone, Copy)]
1100pub enum RelayWeight {
1101 Unmeasured(u32),
1103 Measured(u32),
1105}
1106
1107#[derive(Debug, Clone, thiserror::Error)]
1109#[non_exhaustive]
1110pub enum InvalidRelayWeights {
1111 #[error("invalid value for Unmeasured")]
1113 InvalidUnmeasured,
1114}
1115
1116#[deprecated = "renamed to ConsensusAuthorityEntry"]
1118pub type ConsensusVoterInfo = ConsensusAuthorityEntry;
1119
1120pub type PlainAuthorityEntry = ConsensusAuthorityEntry;
1122pub type MdAuthorityEntry = ConsensusAuthorityEntry;
1124
1125#[derive(Debug, Clone, Deftly)]
1135#[derive_deftly(Constructor, NetdocEncodable, NetdocParseable)]
1136#[allow(clippy::exhaustive_structs)]
1137pub struct ConsensusAuthorityEntry {
1138 #[deftly(constructor)]
1140 pub dir_source: DirSource,
1141
1142 #[deftly(constructor)]
1148 pub contact: ContactInfo,
1149
1150 #[deftly(netdoc(single_arg))]
1157 #[deftly(constructor)]
1158 pub vote_digest: B16U,
1159
1160 #[doc(hidden)]
1161 #[deftly(netdoc(skip))]
1162 pub __non_exhaustive: (),
1163}
1164
1165#[derive(Debug, Clone, Deftly)]
1171#[derive_deftly(Constructor, NetdocEncodable, NetdocParseable)]
1172#[allow(clippy::exhaustive_structs)]
1173pub struct VoteAuthorityEntry {
1174 #[deftly(constructor)]
1176 pub dir_source: DirSource,
1177
1178 #[deftly(constructor)]
1180 pub contact: ContactInfo,
1181
1182 #[deftly(netdoc(single_arg))]
1186 pub legacy_dir_key: Option<Fingerprint>,
1187
1188 pub shared_rand_participate: Option<SharedRandParticipate>,
1192
1193 pub shared_rand_commit: Vec<SharedRandCommit>,
1197
1198 #[deftly(netdoc(flatten))]
1200 pub shared_rand: SharedRandStatuses,
1201
1202 #[doc(hidden)]
1203 #[deftly(netdoc(skip))]
1204 pub __non_exhaustive: (),
1205}
1206
1207#[derive(Debug, Clone, Deftly)]
1217#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
1218#[allow(clippy::exhaustive_structs)]
1219pub struct SharedRandParticipate {
1220 #[doc(hidden)]
1221 #[deftly(netdoc(skip))]
1222 pub __non_exhaustive: (),
1223}
1224
1225#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deftly)]
1229#[allow(clippy::exhaustive_enums)]
1231pub enum SharedRandCommit {
1232 V1(SharedRandCommitV1),
1234
1235 Unknown {},
1238}
1239
1240#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deftly)]
1249#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
1250#[allow(clippy::exhaustive_structs)]
1251pub struct SharedRandCommitV1 {
1252 #[deftly(constructor)]
1255 h_kp_auth_id_rsa: Fingerprint,
1256
1257 #[deftly(constructor)]
1265 commit: FixedB64<40>,
1266
1267 reveal: Option<FixedB64<40>>,
1272
1273 #[doc(hidden)]
1274 #[deftly(netdoc(skip))]
1275 pub __non_exhaustive: (),
1276}
1277
1278impl SharedRandCommitV1 {
1279 const FIXED_ARGUMENTS: &[&str] = &["1", "sha3-256"];
1281}
1282impl ItemValueEncodable for SharedRandCommit {
1283 fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
1284 match self {
1285 SharedRandCommit::V1(values) => {
1286 for fixed in SharedRandCommitV1::FIXED_ARGUMENTS {
1287 out.args_raw_string(fixed);
1288 }
1289 values.write_item_value_onto(out)
1290 }
1291 SharedRandCommit::Unknown {} => Err(internal!("encoding SharedRandCommit::Unknown")),
1292 }
1293 }
1294}
1295impl ItemValueParseable for SharedRandCommit {
1296 fn from_unparsed(mut item: UnparsedItem<'_>) -> Result<Self, ErrorProblem> {
1297 let mut fixed = SharedRandCommitV1::FIXED_ARGUMENTS.iter().copied();
1298 let args = item.args_mut();
1299 let version = args
1300 .next()
1301 .ok_or_else(|| args.handle_error("version", ArgumentError::Missing))?;
1302 if version != fixed.next().expect("nonempty") {
1303 return Ok(SharedRandCommit::Unknown {});
1304 }
1305 for exp in fixed {
1306 let got = args
1307 .next()
1308 .ok_or_else(|| args.handle_error(exp, ArgumentError::Missing))?;
1309 if got != exp {
1310 Err(args.handle_error(exp, ArgumentError::Invalid))?;
1311 }
1312 }
1313 let values = SharedRandCommitV1::from_unparsed(item)?;
1314 Ok(SharedRandCommit::V1(values))
1315 }
1316}
1317
1318define_derive_deftly! {
1321 VoteAuthoritySection:
1333
1334 ${defcond F_NORMAL not(fmeta(netdoc(skip)))}
1335
1336 impl NetdocParseable for VoteAuthoritySection {
1337 fn doctype_for_error() -> &'static str {
1338 "vote.authority.section"
1339 }
1340 fn is_intro_item_keyword(kw: KeywordRef<'_>) -> bool {
1341 VoteAuthorityEntry::is_intro_item_keyword(kw)
1342 }
1343 fn is_structural_keyword(kw: KeywordRef<'_>) -> Option<IsStructural> {
1344 $(
1345 ${when F_NORMAL}
1346 if let y @ Some(_) = $ftype::is_structural_keyword(kw) {
1347 return y;
1348 }
1349 )
1350 None
1351 }
1352 fn from_items<'s>(
1353 input: &mut ItemStream<'s>,
1354 stop_outer: stop_at!(),
1355 ) -> Result<Self, ErrorProblem> {
1356 let stop_inner = stop_outer
1357 $(
1358 ${when F_NORMAL}
1359 | StopAt($ftype::is_intro_item_keyword)
1360 )
1361 ;
1362 Ok(VoteAuthoritySection { $(
1363 ${when F_NORMAL}
1364 $fname: NetdocParseable::from_items(input, stop_inner)?,
1365 )
1366 __non_exhaustive: (),
1367 })
1368 }
1369 }
1370
1371 impl NetdocEncodable for VoteAuthoritySection {
1372 fn encode_unsigned(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
1373 $(
1374 ${when F_NORMAL}
1375 self.$fname.encode_unsigned(out)?;
1376 )
1377 Ok(())
1378 }
1379 }
1380}
1381
1382#[derive(Deftly, Clone, Debug)]
1389#[derive_deftly(VoteAuthoritySection, Constructor)]
1390#[allow(clippy::exhaustive_structs)]
1391pub struct VoteAuthoritySection {
1392 #[deftly(constructor)]
1394 pub authority: VoteAuthorityEntry,
1395
1396 #[deftly(constructor)]
1398 pub cert: EmbeddedCert<AuthCert, EncodedAuthCert>,
1399
1400 #[doc(hidden)]
1401 #[deftly(netdoc(skip))]
1402 pub __non_exhaustive: (),
1403}
1404
1405#[derive(Debug, Clone, Deftly)]
1411#[derive_deftly(Constructor, NetdocEncodableFields, NetdocParseableFields)]
1412#[allow(clippy::exhaustive_structs)]
1413pub struct ConsensusFooterFields {
1414 #[deftly(netdoc(default))]
1418 pub bandwidth_weights: NetParams<i32>,
1419
1420 #[doc(hidden)]
1421 #[deftly(netdoc(skip))]
1422 pub __non_exhaustive: (),
1423}
1424
1425pub type MdConsensus = md::Consensus;
1428
1429pub type UnvalidatedMdConsensus = md::UnvalidatedConsensus;
1432
1433pub type UncheckedMdConsensus = md::UncheckedConsensus;
1436
1437pub type PlainConsensus = plain::Consensus;
1440
1441pub type UnvalidatedPlainConsensus = plain::UnvalidatedConsensus;
1444
1445pub type UncheckedPlainConsensus = plain::UncheckedConsensus;
1448
1449decl_keyword! {
1450 #[non_exhaustive]
1455 #[allow(missing_docs)]
1456 pub NetstatusKwd {
1457 "network-status-version" => NETWORK_STATUS_VERSION,
1459 "vote-status" => VOTE_STATUS,
1460 "consensus-methods" => CONSENSUS_METHODS,
1461 "consensus-method" => CONSENSUS_METHOD,
1462 "published" => PUBLISHED,
1463 "valid-after" => VALID_AFTER,
1464 "fresh-until" => FRESH_UNTIL,
1465 "valid-until" => VALID_UNTIL,
1466 "voting-delay" => VOTING_DELAY,
1467 "client-versions" => CLIENT_VERSIONS,
1468 "server-versions" => SERVER_VERSIONS,
1469 "known-flags" => KNOWN_FLAGS,
1470 "flag-thresholds" => FLAG_THRESHOLDS,
1471 "recommended-client-protocols" => RECOMMENDED_CLIENT_PROTOCOLS,
1472 "required-client-protocols" => REQUIRED_CLIENT_PROTOCOLS,
1473 "recommended-relay-protocols" => RECOMMENDED_RELAY_PROTOCOLS,
1474 "required-relay-protocols" => REQUIRED_RELAY_PROTOCOLS,
1475 "params" => PARAMS,
1476 "bandwidth-file-headers" => BANDWIDTH_FILE_HEADERS,
1477 "bandwidth-file-digest" => BANDWIDTH_FILE_DIGEST,
1478 "shared-rand-previous-value" => SHARED_RAND_PREVIOUS_VALUE,
1482 "shared-rand-current-value" => SHARED_RAND_CURRENT_VALUE,
1483
1484 "dir-source" => DIR_SOURCE,
1486 "contact" => CONTACT,
1487
1488 "legacy-dir-key" => LEGACY_DIR_KEY,
1490 "shared-rand-participate" => SHARED_RAND_PARTICIPATE,
1491 "shared-rand-commit" => SHARED_RAND_COMMIT,
1492
1493 "vote-digest" => VOTE_DIGEST,
1495
1496 "dir-key-certificate-version" => DIR_KEY_CERTIFICATE_VERSION,
1498
1499 "r" => RS_R,
1501 "a" => RS_A,
1502 "s" => RS_S,
1503 "v" => RS_V,
1504 "pr" => RS_PR,
1505 "w" => RS_W,
1506 "p" => RS_P,
1507 "m" => RS_M,
1508 "id" => RS_ID,
1509
1510 "directory-footer" => DIRECTORY_FOOTER,
1512 "bandwidth-weights" => BANDWIDTH_WEIGHTS,
1513 "directory-signature" => DIRECTORY_SIGNATURE,
1514 }
1515}
1516
1517static NS_HEADER_RULES_COMMON_: LazyLock<SectionRulesBuilder<NetstatusKwd>> = LazyLock::new(|| {
1519 use NetstatusKwd::*;
1520 let mut rules = SectionRules::builder();
1521 rules.add(NETWORK_STATUS_VERSION.rule().required().args(1..=2));
1522 rules.add(VOTE_STATUS.rule().required().args(1..));
1523 rules.add(VALID_AFTER.rule().required());
1524 rules.add(FRESH_UNTIL.rule().required());
1525 rules.add(VALID_UNTIL.rule().required());
1526 rules.add(VOTING_DELAY.rule().args(2..));
1527 rules.add(CLIENT_VERSIONS.rule());
1528 rules.add(SERVER_VERSIONS.rule());
1529 rules.add(KNOWN_FLAGS.rule().required());
1530 rules.add(RECOMMENDED_CLIENT_PROTOCOLS.rule().args(1..));
1531 rules.add(RECOMMENDED_RELAY_PROTOCOLS.rule().args(1..));
1532 rules.add(REQUIRED_CLIENT_PROTOCOLS.rule().args(1..));
1533 rules.add(REQUIRED_RELAY_PROTOCOLS.rule().args(1..));
1534 rules.add(PARAMS.rule());
1535 rules
1536});
1537static NS_HEADER_RULES_CONSENSUS: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1539 use NetstatusKwd::*;
1540 let mut rules = NS_HEADER_RULES_COMMON_.clone();
1541 rules.add(CONSENSUS_METHOD.rule().args(1..=1));
1542 rules.add(SHARED_RAND_PREVIOUS_VALUE.rule().args(2..));
1543 rules.add(SHARED_RAND_CURRENT_VALUE.rule().args(2..));
1544 rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1545 rules.build()
1546});
1547static NS_VOTERINFO_RULES_CONSENSUS: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1578 use NetstatusKwd::*;
1579 let mut rules = SectionRules::builder();
1580 rules.add(DIR_SOURCE.rule().required().args(6..));
1581 rules.add(CONTACT.rule().required());
1582 rules.add(VOTE_DIGEST.rule().required());
1583 rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1584 rules.build()
1585});
1586static NS_ROUTERSTATUS_RULES_COMMON_: LazyLock<SectionRulesBuilder<NetstatusKwd>> =
1588 LazyLock::new(|| {
1589 use NetstatusKwd::*;
1590 let mut rules = SectionRules::builder();
1591 rules.add(RS_A.rule().may_repeat().args(1..));
1592 rules.add(RS_S.rule().required());
1593 rules.add(RS_V.rule());
1594 rules.add(RS_PR.rule().required());
1595 rules.add(RS_W.rule());
1596 rules.add(RS_P.rule().args(2..));
1597 rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1598 rules
1599 });
1600
1601static NS_ROUTERSTATUS_RULES_PLAIN: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1603 use NetstatusKwd::*;
1604 let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
1605 rules.add(RS_R.rule().required().args(8..));
1606 rules.build()
1607});
1608
1609static NS_ROUTERSTATUS_RULES_MDCON: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1622 use NetstatusKwd::*;
1623 let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
1624 rules.add(RS_R.rule().required().args(6..));
1625 rules.add(RS_M.rule().required().args(1..));
1626 rules.build()
1627});
1628static NS_FOOTER_RULES: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1630 use NetstatusKwd::*;
1631 let mut rules = SectionRules::builder();
1632 rules.add(DIRECTORY_FOOTER.rule().required().no_args());
1633 rules.add(BANDWIDTH_WEIGHTS.rule());
1635 rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1636 rules.build()
1637});
1638
1639impl ProtoStatus {
1640 fn from_section(
1642 sec: &Section<'_, NetstatusKwd>,
1643 recommend_token: NetstatusKwd,
1644 required_token: NetstatusKwd,
1645 ) -> crate::Result<ProtoStatus> {
1646 fn parse(t: Option<&Item<'_, NetstatusKwd>>) -> crate::Result<Protocols> {
1648 if let Some(item) = t {
1649 item.args_as_str()
1650 .parse::<Protocols>()
1651 .map_err(|e| EK::BadArgument.at_pos(item.pos()).with_source(e))
1652 } else {
1653 Ok(Protocols::new())
1654 }
1655 }
1656
1657 let recommended = parse(sec.get(recommend_token))?;
1658 let required = parse(sec.get(required_token))?;
1659 Ok(ProtoStatus {
1660 recommended,
1661 required,
1662 })
1663 }
1664
1665 pub fn required_protocols(&self) -> &Protocols {
1672 &self.required
1673 }
1674
1675 pub fn recommended_protocols(&self) -> &Protocols {
1680 &self.recommended
1681 }
1682}
1683
1684impl<T> std::str::FromStr for NetParams<T>
1685where
1686 T: std::str::FromStr,
1687 T::Err: std::error::Error,
1688{
1689 type Err = Error;
1690 fn from_str(s: &str) -> crate::Result<Self> {
1691 fn parse_pair<U>(p: &str) -> crate::Result<(String, U)>
1693 where
1694 U: std::str::FromStr,
1695 U::Err: std::error::Error,
1696 {
1697 let parts: Vec<_> = p.splitn(2, '=').collect();
1698 if parts.len() != 2 {
1699 return Err(EK::BadArgument
1700 .at_pos(Pos::at(p))
1701 .with_msg("Missing = in key=value list"));
1702 }
1703 let num = parts[1].parse::<U>().map_err(|e| {
1704 EK::BadArgument
1705 .at_pos(Pos::at(parts[1]))
1706 .with_msg(e.to_string())
1707 })?;
1708 Ok((parts[0].to_string(), num))
1709 }
1710
1711 let params = s
1712 .split(' ')
1713 .filter(|p| !p.is_empty())
1714 .map(parse_pair)
1715 .try_collect()?;
1716 Ok(NetParams { params })
1717 }
1718}
1719
1720impl FromStr for SharedRandVal {
1721 type Err = Error;
1722 fn from_str(s: &str) -> crate::Result<Self> {
1723 let val: B64 = s.parse()?;
1724 let val = SharedRandVal(val.into_array()?);
1725 Ok(val)
1726 }
1727}
1728impl Display for SharedRandVal {
1729 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1730 Display::fmt(&B64::from(Vec::from(self.0)), f)
1731 }
1732}
1733impl NormalItemArgument for SharedRandVal {}
1734
1735impl SharedRandStatus {
1736 fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Self> {
1739 match item.kwd() {
1740 NetstatusKwd::SHARED_RAND_PREVIOUS_VALUE | NetstatusKwd::SHARED_RAND_CURRENT_VALUE => {}
1741 _ => {
1742 return Err(Error::from(internal!(
1743 "wrong keyword {:?} on shared-random value",
1744 item.kwd()
1745 ))
1746 .at_pos(item.pos()));
1747 }
1748 }
1749 let n_reveals: u8 = item.parse_arg(0)?;
1750 let value: SharedRandVal = item.parse_arg(1)?;
1751 let timestamp = item.parse_optional_arg::<Iso8601TimeNoSp>(2)?;
1753 Ok(SharedRandStatus {
1754 n_reveals,
1755 value,
1756 timestamp,
1757 })
1758 }
1759
1760 pub fn value(&self) -> &SharedRandVal {
1762 &self.value
1763 }
1764
1765 pub fn timestamp(&self) -> Option<std::time::SystemTime> {
1767 self.timestamp.map(|t| t.0)
1768 }
1769}
1770
1771impl DirSource {
1772 fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Self> {
1774 if item.kwd() != NetstatusKwd::DIR_SOURCE {
1775 return Err(
1776 Error::from(internal!("Bad keyword {:?} on dir-source", item.kwd()))
1777 .at_pos(item.pos()),
1778 );
1779 }
1780 let nickname = item
1781 .required_arg(0)?
1782 .parse()
1783 .map_err(|e: InvalidNickname| {
1784 EK::BadArgument.at_pos(item.pos()).with_msg(e.to_string())
1785 })?;
1786 let identity = item.parse_arg(1)?;
1787 let hostname = item
1788 .required_arg(2)?
1789 .parse()
1790 .map_err(|e: InvalidInternetHost| {
1791 EK::BadArgument.at_pos(item.pos()).with_msg(e.to_string())
1792 })?;
1793 let ip = item.parse_arg(3)?;
1794 let dir_port = item.parse_arg(4)?;
1795 let or_port = item.parse_arg(5)?;
1796
1797 Ok(DirSource {
1798 nickname,
1799 identity,
1800 hostname,
1801 ip,
1802 dir_port,
1803 or_port,
1804 __non_exhaustive: (),
1805 })
1806 }
1807}
1808
1809impl ConsensusAuthorityEntry {
1810 fn from_section(sec: &Section<'_, NetstatusKwd>) -> crate::Result<ConsensusAuthorityEntry> {
1812 use NetstatusKwd::*;
1813 #[allow(clippy::unwrap_used)]
1816 let first = sec.first_item().unwrap();
1817 if first.kwd() != DIR_SOURCE {
1818 return Err(Error::from(internal!(
1819 "Wrong keyword {:?} at start of voter info",
1820 first.kwd()
1821 ))
1822 .at_pos(first.pos()));
1823 }
1824 let dir_source = DirSource::from_item(sec.required(DIR_SOURCE)?)?;
1825
1826 let contact = sec.required(CONTACT)?;
1827 let contact = contact
1833 .args_as_str()
1834 .parse()
1835 .map_err(|err: InvalidContactInfo| {
1836 EK::BadArgument
1837 .with_msg(err.to_string())
1838 .at_pos(contact.pos())
1839 })?;
1840
1841 let vote_digest = sec.required(VOTE_DIGEST)?.parse_arg::<B16U>(0)?;
1842
1843 Ok(ConsensusAuthorityEntry {
1844 dir_source,
1845 contact,
1846 vote_digest,
1847 __non_exhaustive: (),
1848 })
1849 }
1850}
1851
1852impl RelayWeightsItem {
1853 pub fn new_no_info() -> Self {
1857 RelayWeightsItem {
1858 effective: RelayWeight::default(),
1859 params: Unknown::new_discard(),
1860 }
1861 }
1862
1863 pub fn from_effective(effective: RelayWeight) -> Self {
1865 RelayWeightsItem {
1866 effective,
1867 params: Unknown::new_discard(),
1868 }
1869 }
1870
1871 pub fn effective(&self) -> RelayWeight {
1878 self.effective
1879 }
1880
1881 pub fn params(&self) -> Unknown<&Option<NetParams<u32>>> {
1889 self.params.as_ref()
1890 }
1891
1892 fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<RelayWeightsItem> {
1894 if item.kwd() != NetstatusKwd::RS_W {
1895 return Err(
1896 Error::from(internal!("Wrong keyword {:?} on W line", item.kwd()))
1897 .at_pos(item.pos()),
1898 );
1899 }
1900
1901 let params = item.args_as_str().parse()?;
1902 let effective = RelayWeight::from_net_params(¶ms).map_err(|e| e.at_pos(item.pos()))?;
1903
1904 Ok(RelayWeightsItem {
1905 effective,
1906 params: Unknown::new_discard(),
1907 })
1908 }
1909
1910 const KEYWORD: &str = "w";
1912}
1913
1914#[cfg(feature = "retain-unknown")]
1915impl Default for RelayWeightsItem {
1916 fn default() -> Self {
1917 RelayWeightsItem {
1918 effective: RelayWeight::default(),
1919 params: Unknown::Retained(None),
1920 }
1921 }
1922}
1923
1924impl RelayWeight {
1925 pub fn is_measured(&self) -> bool {
1927 matches!(self, RelayWeight::Measured(_))
1928 }
1929
1930 pub fn is_nonzero(&self) -> bool {
1932 !matches!(self, RelayWeight::Unmeasured(0) | RelayWeight::Measured(0))
1933 }
1934
1935 fn from_net_params(params: &NetParams<u32>) -> crate::Result<RelayWeight> {
1939 params
1940 .try_into()
1941 .map_err(|e: InvalidRelayWeights| EK::BadArgument.with_msg(e.to_string()))
1942 }
1943}
1944
1945impl Default for RelayWeight {
1946 fn default() -> RelayWeight {
1947 RelayWeight::Unmeasured(0)
1948 }
1949}
1950
1951impl TryFrom<&NetParams<u32>> for RelayWeight {
1952 type Error = InvalidRelayWeights;
1953
1954 fn try_from(params: &NetParams<u32>) -> Result<RelayWeight, InvalidRelayWeights> {
1955 let bw = params.params.get("Bandwidth");
1956 let unmeas = params.params.get("Unmeasured");
1957
1958 let bw = match bw {
1959 None => return Ok(RelayWeight::Unmeasured(0)),
1960 Some(b) => *b,
1961 };
1962
1963 match unmeas {
1964 None | Some(0) => Ok(RelayWeight::Measured(bw)),
1965 Some(1) => Ok(RelayWeight::Unmeasured(bw)),
1966 _ => Err(InvalidRelayWeights::InvalidUnmeasured),
1967 }
1968 }
1969}
1970
1971#[cfg(feature = "retain-unknown")]
1972impl TryFrom<NetParams<u32>> for RelayWeightsItem {
1973 type Error = InvalidRelayWeights;
1974
1975 fn try_from(params: NetParams<u32>) -> Result<RelayWeightsItem, InvalidRelayWeights> {
1976 Ok(RelayWeightsItem {
1977 effective: (¶ms).try_into()?,
1978 params: Unknown::Retained(Some(params)),
1979 })
1980 }
1981}
1982
1983mod parse2_impls {
1987 use super::*;
1988 pub(super) use parse2::{
1989 ArgumentError as AE, ArgumentStream, ErrorProblem as EP, ItemArgumentParseable,
1990 ItemValueParseable, NetdocParseableFields,
1991 };
1992 use std::result::Result;
1993
1994 impl<T: FromStr + NormalItemArgument> ItemValueParseable for NetParams<T>
1996 where
1997 T::Err: std::error::Error,
1998 {
1999 fn from_unparsed(item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
2000 item.check_no_object()?;
2001 item.args_copy()
2002 .into_remaining()
2003 .parse()
2004 .map_err(item.invalid_argument_handler("parameters"))
2005 }
2006 }
2007
2008 impl NetdocParseableFields for RelayWeightsItem {
2009 type Accumulator = Option<NetParams<u32>>;
2010
2011 fn is_item_keyword(kw: KeywordRef) -> bool {
2012 kw == Self::KEYWORD
2013 }
2014
2015 fn accumulate_item(acc: &mut Self::Accumulator, item: UnparsedItem) -> Result<(), EP> {
2016 if acc.is_some() {
2017 return Err(EP::ItemRepeated);
2018 }
2019 item.check_no_object()?;
2020 let params = NetParams::from_unparsed(item)?;
2021 *acc = Some(params);
2022 Ok(())
2023 }
2024
2025 fn finish(params: Self::Accumulator, items: &ItemStream) -> Result<Self, EP> {
2026 let effective = params
2027 .as_ref()
2028 .map(TryFrom::try_from)
2029 .transpose()
2030 .map_err(|_| EP::OtherBadDocument("invalid information in `w` item"))?
2031 .unwrap_or_default();
2032
2033 let params = items.parse_options().retain_unknown_values.map(|()| params);
2034
2035 Ok(RelayWeightsItem { effective, params })
2036 }
2037 }
2038
2039 impl ItemValueParseable for rs::SoftwareVersion {
2040 fn from_unparsed(mut item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
2041 item.check_no_object()?;
2042 item.args_mut()
2043 .into_remaining()
2044 .parse()
2045 .map_err(item.invalid_argument_handler("version"))
2046 }
2047 }
2048
2049 impl ItemArgumentParseable for IgnoredPublicationTimeSp {
2050 fn from_args(a: &mut ArgumentStream) -> Result<IgnoredPublicationTimeSp, AE> {
2051 let mut next_arg = || a.next().ok_or(AE::Missing);
2052 let _: &str = next_arg()?;
2053 let _: &str = next_arg()?;
2054 Ok(IgnoredPublicationTimeSp)
2055 }
2056 }
2057}
2058
2059mod encode_impls {
2063 use super::*;
2064 use std::result::Result;
2065 pub(crate) use {
2066 crate::encode::{ItemEncoder, ItemValueEncodable, NetdocEncodableFields},
2067 tor_error::Bug,
2068 };
2069
2070 impl NetdocEncodableFields for RelayWeightsItem {
2071 fn encode_fields(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
2072 if let Some(w) = self.params.as_ref().into_retained()? {
2073 w.write_item_value_onto(out.item(Self::KEYWORD))?;
2074 }
2075 Ok(())
2076 }
2077 }
2078
2079 impl<T: NormalItemArgument + Ord + Display> ItemValueEncodable for NetParams<T> {
2081 fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
2082 for (k, v) in self.iter().collect::<BTreeSet<_>>() {
2083 if k.is_empty()
2084 || k.chars()
2085 .any(|c| c.is_whitespace() || c.is_control() || c == '=')
2086 {
2087 return Err(bad_api_usage!(
2089 "tried to encode NetParms with unreasonable keyword {k:?}"
2090 ));
2091 }
2092 out.args_raw_string(&format_args!("{k}={v}"));
2093 }
2094 Ok(())
2095 }
2096 }
2097
2098 impl ItemValueEncodable for rs::SoftwareVersion {
2099 fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
2100 out.args_raw_string(self);
2101 Ok(())
2102 }
2103 }
2104
2105 impl ItemArgument for IgnoredPublicationTimeSp {
2106 fn write_arg_onto(&self, out: &mut ItemEncoder) -> Result<(), Bug> {
2107 out.args_raw_string(&"2000-01-01 00:00:01");
2108 Ok(())
2109 }
2110 }
2111}
2112
2113impl ConsensusFooterFields {
2114 fn from_section(sec: &Section<'_, NetstatusKwd>) -> crate::Result<ConsensusFooterFields> {
2116 use NetstatusKwd::*;
2117 sec.required(DIRECTORY_FOOTER)?;
2118
2119 let bandwidth_weights = sec
2120 .maybe(BANDWIDTH_WEIGHTS)
2121 .args_as_str()
2122 .unwrap_or("")
2123 .parse()?;
2124
2125 Ok(ConsensusFooterFields {
2126 bandwidth_weights,
2127 __non_exhaustive: (),
2128 })
2129 }
2130}
2131
2132mod proto_statuses_parse2_encode {
2136 use super::encode_impls::*;
2137 use super::parse2_impls::*;
2138 use super::*;
2139 use paste::paste;
2140 use std::result::Result;
2141
2142 macro_rules! impl_proto_statuses { { $( $rr:ident $cr:ident; )* } => { paste! {
2156 #[derive(Deftly)]
2157 #[derive_deftly(NetdocParseableFields)]
2158 #[allow(unreachable_pub)]
2160 pub struct ProtoStatusesParseHelper {
2161 $(
2162 #[deftly(netdoc(default))]
2163 [<$rr _ $cr _protocols>]: Protocols,
2164 )*
2165 }
2166
2167 pub use ProtoStatusesParseHelperNetdocParseAccumulator
2169 as ProtoStatusesNetdocParseAccumulator;
2170
2171 impl NetdocParseableFields for ProtoStatuses {
2172 type Accumulator = ProtoStatusesNetdocParseAccumulator;
2173 fn is_item_keyword(kw: KeywordRef<'_>) -> bool {
2174 ProtoStatusesParseHelper::is_item_keyword(kw)
2175 }
2176 fn accumulate_item(
2177 acc: &mut Self::Accumulator,
2178 item: UnparsedItem<'_>,
2179 ) -> Result<(), EP> {
2180 ProtoStatusesParseHelper::accumulate_item(acc, item)
2181 }
2182 fn finish(acc: Self::Accumulator, items: &ItemStream<'_>) -> Result<Self, EP> {
2183 let parse = ProtoStatusesParseHelper::finish(acc, items)?;
2184 let mut out = ProtoStatuses::default();
2185 $(
2186 out.$cr.$rr = parse.[< $rr _ $cr _protocols >];
2187 )*
2188 Ok(out)
2189 }
2190 }
2191
2192 impl NetdocEncodableFields for ProtoStatuses {
2193 fn encode_fields(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
2194 $(
2195 self.$cr.$rr.write_item_value_onto(
2196 out.item(concat!(stringify!($rr), "-", stringify!($cr), "-protocols"))
2197 )?;
2198 )*
2199 Ok(())
2200 }
2201 }
2202 } } }
2203
2204 impl_proto_statuses! {
2205 recommended client;
2206 recommended relay;
2207 required client;
2208 required relay;
2209 }
2210}
2211
2212impl Signature {
2213 fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Signature> {
2215 if item.kwd() != NetstatusKwd::DIRECTORY_SIGNATURE {
2216 return Err(Error::from(internal!(
2217 "Wrong keyword {:?} for directory signature",
2218 item.kwd()
2219 ))
2220 .at_pos(item.pos()));
2221 }
2222
2223 let (digest_algo, id_fp, sk_fp) = if item.n_args() > 2 {
2224 (
2225 item.required_arg(0)?,
2226 item.required_arg(1)?,
2227 item.required_arg(2)?,
2228 )
2229 } else {
2230 ("sha1", item.required_arg(0)?, item.required_arg(1)?)
2232 };
2233
2234 let digest_algo = digest_algo.to_string().parse().void_unwrap();
2235 let digest_algo = DigestAlgoInSignature(Some(digest_algo));
2236 let id_fingerprint = id_fp.parse::<Fingerprint>()?.into();
2237 let sk_fingerprint = sk_fp.parse::<Fingerprint>()?.into();
2238 let key_ids = AuthCertKeyIds {
2239 id_fingerprint,
2240 sk_fingerprint,
2241 };
2242 let signature = item.obj("SIGNATURE")?;
2243
2244 Ok(Signature {
2245 digest_algo,
2246 key_ids,
2247 signature,
2248 })
2249 }
2250
2251 fn matches_cert(&self, cert: &AuthCert) -> bool {
2254 cert.key_ids() == self.key_ids
2255 }
2256
2257 fn find_cert<'a>(&self, certs: &'a [AuthCert]) -> Option<&'a AuthCert> {
2260 certs.iter().find(|&c| self.matches_cert(c))
2261 }
2262
2263 fn signature_to_verify<'r>(
2267 &'r self,
2268 signed_digest: &'r [u8],
2269 certs: &'r [AuthCert],
2270 ) -> Option<ConsensusSignatureToVerify> {
2271 let cert = self.find_cert(certs)?;
2272 let key = cert.signing_key();
2273 Some(ConsensusSignatureToVerify {
2274 key,
2275 signed_digest,
2276 signature: &self.signature,
2277 })
2278 }
2279}
2280
2281impl EncodeOrd for Signature {
2282 fn encode_cmp(&self, other: &Self) -> std::cmp::Ordering {
2283 let k: for<'s> fn(&'_ Signature) -> (&'_ _, &'_ _) = |s| (&s.key_ids, &s.signature);
2284 Ord::cmp(&k(self), &k(other))
2285 }
2286}
2287
2288#[derive(Debug, Clone, Copy)]
2294struct ConsensusSignatureToVerify<'r> {
2295 key: &'r ll::pk::rsa::PublicKey,
2297
2298 signed_digest: &'r [u8],
2300
2301 signature: &'r [u8],
2303}
2304
2305pub(crate) struct SignatureVerifiedIfIntended {}
2314
2315impl<'r> ConsensusSignatureToVerify<'r> {
2316 fn verify(self) -> Result<SignatureVerifiedIfIntended, VerifyFailed> {
2319 self.key.verify(self.signed_digest, self.signature)?;
2320 Ok(SignatureVerifiedIfIntended {})
2321 }
2322}
2323
2324#[derive(Debug, Clone, Copy)]
2328pub(crate) enum VerifyGeneralTrustedAuthorities<'r> {
2329 TrustThese {
2331 trusted: &'r [RsaIdentity],
2333 },
2334
2335 AnyOneOfThese {
2337 trusted: &'r [RsaIdentity],
2339 },
2340
2341 HazardouslyAssumeAllAuthCertsAreReal {
2346 n_authorities: usize,
2350 },
2351}
2352
2353pub fn consensus_threshold(n_authorities: usize) -> std::ops::RangeFrom<usize> {
2383 (n_authorities / 2) + 1 ..
2385}
2386
2387impl SignatureGroup {
2388 fn list_missing(&self, certs: &[AuthCert]) -> (usize, Vec<&Signature>) {
2395 let mut ok: HashSet<RsaIdentity> = HashSet::new();
2396 let mut missing = Vec::new();
2397 for sig in &self.signatures {
2398 let id_fingerprint = &sig.key_ids.id_fingerprint;
2399 if ok.contains(id_fingerprint) {
2400 continue;
2401 }
2402 if sig.find_cert(certs).is_some() {
2403 ok.insert(*id_fingerprint);
2404 continue;
2405 }
2406
2407 missing.push(sig);
2408 }
2409 (ok.len(), missing)
2410 }
2411
2412 fn could_validate(&self, authorities: &[&RsaIdentity]) -> bool {
2416 let mut signed_by: HashSet<RsaIdentity> = HashSet::new();
2417 for sig in &self.signatures {
2418 let id_fp = &sig.key_ids.id_fingerprint;
2419 if signed_by.contains(id_fp) {
2420 continue;
2422 }
2423 if authorities.contains(&id_fp) {
2424 signed_by.insert(*id_fp);
2425 }
2426 }
2427
2428 consensus_threshold(authorities.len()).contains(&signed_by.len())
2429 }
2430
2431 fn validate(&self, n_authorities: usize, certs: &[AuthCert]) -> Result<(), VerifyFailed> {
2438 self.verify_general(
2441 VerifyGeneralTrustedAuthorities::HazardouslyAssumeAllAuthCertsAreReal { n_authorities },
2442 certs,
2443 |tv| tv.verify(),
2444 )
2445 }
2446
2447 fn verify_general<E>(
2476 &self,
2477 trusted_authorities: VerifyGeneralTrustedAuthorities,
2478 certs: &[AuthCert],
2479 do_verify: impl Fn(ConsensusSignatureToVerify) -> Result<SignatureVerifiedIfIntended, E>,
2480 ) -> Result<(), E>
2481 where
2482 ConsensusVerifiabilityError: Into<E>,
2483 {
2484 use VerifyGeneralTrustedAuthorities as TA;
2485
2486 let mut ok: HashSet<RsaIdentity> = HashSet::new();
2490 let mut missing = HashSet::new();
2491 let mut verify_failed = Ok(());
2492
2493 for sig in &self.signatures {
2494 let Signature {
2496 digest_algo,
2497 key_ids:
2498 AuthCertKeyIds {
2499 id_fingerprint,
2500 sk_fingerprint: _,
2503 },
2504 signature: _,
2506 } = sig;
2507
2508 match trusted_authorities {
2509 TA::TrustThese { trusted } | TA::AnyOneOfThese { trusted } => {
2510 if !trusted.contains(id_fingerprint) {
2511 continue;
2512 }
2513 }
2514 TA::HazardouslyAssumeAllAuthCertsAreReal { .. } => {
2515 }
2517 }
2518
2519 if ok.contains(id_fingerprint) {
2520 continue;
2523 }
2524
2525 let Some(d) = self.hashes.hash_slice_for_verification(digest_algo) else {
2526 continue;
2529 };
2530
2531 let Some(tv) = sig.signature_to_verify(d, certs) else {
2532 missing.insert(sig.key_ids);
2533 continue;
2534 };
2535 match do_verify(tv) {
2536 Ok::<SignatureVerifiedIfIntended, _>(_) => {
2537 ok.insert(*id_fingerprint);
2538 }
2539 Err(e) => {
2540 verify_failed = Err(e);
2541 }
2542 }
2543 }
2544
2545 let n_authorities = match trusted_authorities {
2546 TA::TrustThese { trusted } => trusted.len(),
2547 TA::HazardouslyAssumeAllAuthCertsAreReal { n_authorities: n } => n,
2548 TA::AnyOneOfThese { .. } => {
2549 1
2553 }
2554 };
2555 let threshold = consensus_threshold(n_authorities);
2556
2557 if threshold.contains(&ok.len()) {
2558 Ok(())
2559 } else {
2560 verify_failed?;
2562
2563 Err(if missing.is_empty() {
2565 ConsensusVerifiabilityError::InsufficientTrustedSigners
2566 } else {
2567 let deficit = threshold.start - ok.len();
2568 ConsensusVerifiabilityError::MissingAuthCerts { missing, deficit }
2569 }
2570 .into())
2571 }
2572 }
2573}
2574
2575impl From<ConsensusVerifiabilityError> for VerifyFailed {
2576 fn from(cve: ConsensusVerifiabilityError) -> VerifyFailed {
2577 use ConsensusVerifiabilityError as CVE;
2578 use VerifyFailed as VF;
2579 match cve {
2580 CVE::InsufficientTrustedSigners => VF::InsufficientTrustedSigners,
2581 CVE::MissingAuthCerts { .. } => VF::InsufficientTrustedSigners,
2582 }
2583 }
2584}
2585
2586impl From<ConsensusVerifyFailed> for VerifyFailed {
2587 fn from(cvf: ConsensusVerifyFailed) -> VerifyFailed {
2588 use ConsensusVerifyFailed as CVF;
2589 use VerifyFailed as VF;
2590 match cvf {
2591 CVF::CertificationInsufficient { .. } => VF::InsufficientTrustedSigners,
2592 CVF::InvalidSignature { .. } => VF::VerifyFailed,
2593 }
2594 }
2595}
2596
2597#[cfg(test)]
2598mod test {
2599 #![allow(clippy::bool_assert_comparison)]
2601 #![allow(clippy::clone_on_copy)]
2602 #![allow(clippy::dbg_macro)]
2603 #![allow(clippy::mixed_attributes_style)]
2604 #![allow(clippy::print_stderr)]
2605 #![allow(clippy::print_stdout)]
2606 #![allow(clippy::single_char_pattern)]
2607 #![allow(clippy::unwrap_used)]
2608 #![allow(clippy::unchecked_time_subtraction)]
2609 #![allow(clippy::useless_vec)]
2610 #![allow(clippy::needless_pass_by_value)]
2611 #![allow(clippy::string_slice)] use super::*;
2614 use crate::doc::authcert::AuthCertUnverified;
2615 use crate::encode::{NetdocEncodable, NetdocEncodableFields};
2616 use crate::parse2::{ParseInput, parse_netdoc, parse_netdoc_multiple};
2617 use crate::test_support::regsub;
2618 use anyhow::Context as _;
2619 use assert_matches::assert_matches;
2620 use hex_literal::hex;
2621 use humantime::parse_rfc3339;
2622 use std::fmt::Debug;
2623 use std::fs;
2624 use std::time::Duration;
2625 use tor_checkable::TimeBound;
2626
2627 const CERTS: &str = include_str!("../../testdata/authcerts2.txt");
2628 const CONSENSUS: &str = include_str!("../../testdata/mdconsensus1.txt");
2629
2630 const PLAIN_CERTS: &str = include_str!("../../testdata2/cached-certs");
2631 const PLAIN_CONSENSUS: &str = include_str!("../../testdata2/cached-consensus");
2632
2633 fn read_bad(fname: &str) -> String {
2634 use std::fs;
2635 use std::path::PathBuf;
2636 let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
2637 path.push("testdata");
2638 path.push("bad-mdconsensus");
2639 path.push(fname);
2640
2641 fs::read_to_string(path).unwrap()
2642 }
2643
2644 #[test]
2645 fn parse_and_validate_md() -> crate::Result<()> {
2646 use std::net::SocketAddr;
2647 use tor_checkable::{SelfSigned, TimeBound};
2648 let mut certs = Vec::new();
2649 for cert in AuthCert::parse_multiple(CERTS)? {
2650 let cert = cert?.check_signature()?.dangerously_assume_timely();
2651 certs.push(cert);
2652 }
2653 let auth_ids: Vec<_> = certs.iter().map(|c| c.id_fingerprint()).collect();
2654
2655 assert_eq!(certs.len(), 3);
2656
2657 let (_, _, consensus) = MdConsensus::parse(CONSENSUS)?;
2658 let consensus = consensus.dangerously_assume_timely().set_n_authorities(3);
2659
2660 assert!(consensus.authorities_are_correct(&auth_ids));
2662 assert!(consensus.authorities_are_correct(&auth_ids[0..1]));
2664 {
2665 let bad_auth_id = (*b"xxxxxxxxxxxxxxxxxxxx").into();
2668 assert!(!consensus.authorities_are_correct(&[&bad_auth_id]));
2669 }
2670
2671 let missing = consensus.key_is_correct(&[]).err().unwrap();
2672 assert_eq!(3, missing.len());
2673 assert!(consensus.key_is_correct(&certs).is_ok());
2674 let missing = consensus.key_is_correct(&certs[0..1]).err().unwrap();
2675 assert_eq!(2, missing.len());
2676
2677 let same_three_times = vec![certs[0].clone(), certs[0].clone(), certs[0].clone()];
2679 let missing = consensus.key_is_correct(&same_three_times).err().unwrap();
2680
2681 assert_eq!(2, missing.len());
2682 assert!(consensus.is_well_signed(&same_three_times).is_err());
2683
2684 assert!(consensus.key_is_correct(&certs).is_ok());
2685 let consensus = consensus.check_signature(&certs)?;
2686
2687 assert_eq!(6, consensus.relays().len());
2688 let r0 = &consensus.relays()[0];
2689 assert_eq!(
2690 r0.md_digest(),
2691 &hex!("73dabe0a0468f4f7a67810a18d11e36731bb1d2ec3634db459100609f3b3f535")
2692 );
2693 assert_eq!(
2694 r0.rsa_identity().as_bytes(),
2695 &hex!("0a3057af2910415794d8ea430309d9ac5f5d524b")
2696 );
2697 assert!(!r0.weight().is_measured());
2698 assert!(!r0.weight().is_nonzero());
2699 let pv = &r0.protovers();
2700 assert!(pv.supports_subver("HSDir", 2));
2701 assert!(!pv.supports_subver("HSDir", 3));
2702 let ip4 = "127.0.0.1:5002".parse::<SocketAddr>().unwrap();
2703 let ip6 = "[::1]:5002".parse::<SocketAddr>().unwrap();
2704 assert!(r0.addrs().any(|a| a == ip4));
2705 assert!(r0.addrs().any(|a| a == ip6));
2706
2707 Ok(())
2708 }
2709
2710 #[test]
2711 fn parse_and_validate_ns() -> crate::Result<()> {
2712 use tor_checkable::{SelfSigned, TimeBound};
2713 let mut certs = Vec::new();
2714 for cert in AuthCert::parse_multiple(PLAIN_CERTS)? {
2715 let cert = cert?.check_signature()?.dangerously_assume_timely();
2716 certs.push(cert);
2717 }
2718 let auth_ids: Vec<_> = certs.iter().map(|c| c.id_fingerprint()).collect();
2719 assert_eq!(certs.len(), 4);
2720
2721 let (_, _, consensus) = PlainConsensus::parse(PLAIN_CONSENSUS)?;
2722 let consensus = consensus.dangerously_assume_timely().set_n_authorities(3);
2723 assert!(consensus.authorities_are_correct(&auth_ids));
2725 assert!(consensus.authorities_are_correct(&auth_ids[0..1]));
2727
2728 assert!(consensus.key_is_correct(&certs).is_ok());
2729
2730 let _consensus = consensus.check_signature(&certs)?;
2731
2732 Ok(())
2733 }
2734
2735 #[test]
2736 fn test_bad() {
2737 use crate::Pos;
2738 fn check(fname: &str, e: &Error) {
2739 let content = read_bad(fname);
2740 let res = MdConsensus::parse(&content);
2741 assert!(res.is_err());
2742 assert_eq!(&res.err().unwrap(), e);
2743 }
2744
2745 check(
2746 "bad-flags",
2747 &EK::BadArgument
2748 .at_pos(Pos::from_line(27, 1))
2749 .with_msg("Flags out of order"),
2750 );
2751 check(
2752 "bad-md-digest",
2753 &EK::BadArgument
2754 .at_pos(Pos::from_line(40, 3))
2755 .with_msg("Invalid base64"),
2756 );
2757 check(
2758 "bad-weight",
2759 &EK::BadArgument
2760 .at_pos(Pos::from_line(67, 141))
2761 .with_msg("invalid digit found in string"),
2762 );
2763 check(
2764 "bad-weights",
2765 &EK::BadArgument
2766 .at_pos(Pos::from_line(51, 13))
2767 .with_msg("invalid digit found in string"),
2768 );
2769 check(
2770 "wrong-order",
2771 &EK::WrongSortOrder.at_pos(Pos::from_line(52, 1)),
2772 );
2773 check(
2774 "wrong-start",
2775 &EK::UnexpectedToken
2776 .with_msg("vote-status")
2777 .at_pos(Pos::from_line(1, 1)),
2778 );
2779 check("wrong-version", &EK::BadDocumentVersion.with_msg("10"));
2780 }
2781
2782 fn gettok(s: &str) -> crate::Result<Item<'_, NetstatusKwd>> {
2783 let mut reader = NetDocReader::new(s)?;
2784 let tok = reader.next().unwrap();
2785 assert!(reader.next().is_none());
2786 tok
2787 }
2788
2789 #[test]
2790 fn test_weight() {
2791 let w = gettok("w Unmeasured=1 Bandwidth=6\n").unwrap();
2792 let w = RelayWeightsItem::from_item(&w).unwrap();
2793 assert!(!w.effective.is_measured());
2794 assert!(w.effective.is_nonzero());
2795
2796 let w = gettok("w Bandwidth=10\n").unwrap();
2797 let w = RelayWeightsItem::from_item(&w).unwrap();
2798 assert!(w.effective.is_measured());
2799 assert!(w.effective.is_nonzero());
2800
2801 let w = RelayWeightsItem::new_no_info();
2802 assert!(!w.effective.is_measured());
2803 assert!(!w.effective.is_nonzero());
2804
2805 let w = gettok("w Mustelid=66 Cheato=7 Unmeasured=1\n").unwrap();
2806 let w = RelayWeightsItem::from_item(&w).unwrap();
2807 assert!(!w.effective.is_measured());
2808 assert!(!w.effective.is_nonzero());
2809
2810 let w = gettok("r foo\n").unwrap();
2811 let w = RelayWeightsItem::from_item(&w);
2812 assert!(w.is_err());
2813
2814 let w = gettok("r Bandwidth=6 Unmeasured=Frog\n").unwrap();
2815 let w = RelayWeightsItem::from_item(&w);
2816 assert!(w.is_err());
2817
2818 let w = gettok("r Bandwidth=6 Unmeasured=3\n").unwrap();
2819 let w = RelayWeightsItem::from_item(&w);
2820 assert!(w.is_err());
2821 }
2822
2823 #[test]
2824 fn test_netparam() {
2825 let p = "Hello=600 Goodbye=5 Fred=7"
2826 .parse::<NetParams<u32>>()
2827 .unwrap();
2828 assert_eq!(p.get("Hello"), Some(&600_u32));
2829
2830 let p = "Hello=Goodbye=5 Fred=7".parse::<NetParams<u32>>();
2831 assert!(p.is_err());
2832
2833 let p = "Hello=Goodbye Fred=7".parse::<NetParams<u32>>();
2834 assert!(p.is_err());
2835
2836 for bad_kw in ["What=The", "", "\n", "\0"] {
2837 let p = [(bad_kw, 42)].into_iter().collect::<NetParams<i32>>();
2838 let mut d = NetdocEncoder::new();
2839 let d = (|| {
2840 let i = d.item("bad-psrams");
2841 p.write_item_value_onto(i)?;
2842 d.finish()
2843 })();
2844 let _: tor_error::Bug = d.expect_err(bad_kw);
2845 }
2846 }
2847
2848 #[test]
2849 fn test_sharedrand() {
2850 let sr =
2851 gettok("shared-rand-previous-value 9 5LodY4yWxFhTKtxpV9wAgNA9N8flhUCH0NqQv1/05y4\n")
2852 .unwrap();
2853 let sr = SharedRandStatus::from_item(&sr).unwrap();
2854
2855 assert_eq!(sr.n_reveals, 9);
2856 assert_eq!(
2857 sr.value.0,
2858 hex!("e4ba1d638c96c458532adc6957dc0080d03d37c7e5854087d0da90bf5ff4e72e")
2859 );
2860 assert!(sr.timestamp.is_none());
2861
2862 let sr2 = gettok(
2863 "shared-rand-current-value 9 \
2864 5LodY4yWxFhTKtxpV9wAgNA9N8flhUCH0NqQv1/05y4 2022-01-20T12:34:56\n",
2865 )
2866 .unwrap();
2867 let sr2 = SharedRandStatus::from_item(&sr2).unwrap();
2868 assert_eq!(sr2.n_reveals, sr.n_reveals);
2869 assert_eq!(sr2.value.0, sr.value.0);
2870 assert_eq!(
2871 sr2.timestamp.unwrap().0,
2872 humantime::parse_rfc3339("2022-01-20T12:34:56Z").unwrap()
2873 );
2874
2875 let sr = gettok("foo bar\n").unwrap();
2876 let sr = SharedRandStatus::from_item(&sr);
2877 assert!(sr.is_err());
2878 }
2879
2880 #[test]
2881 fn test_protostatus() {
2882 let my_protocols: Protocols = "Link=7 Cons=1-5 Desc=3-10".parse().unwrap();
2883
2884 let outcome = ProtoStatus {
2885 recommended: "Link=7".parse().unwrap(),
2886 required: "Desc=5".parse().unwrap(),
2887 }
2888 .check_protocols(&my_protocols);
2889 assert!(outcome.is_ok());
2890
2891 let outcome = ProtoStatus {
2892 recommended: "Microdesc=4 Link=7".parse().unwrap(),
2893 required: "Desc=5".parse().unwrap(),
2894 }
2895 .check_protocols(&my_protocols);
2896 assert_eq!(
2897 outcome,
2898 Err(ProtocolSupportError::MissingRecommended(
2899 "Microdesc=4".parse().unwrap()
2900 ))
2901 );
2902
2903 let outcome = ProtoStatus {
2904 recommended: "Microdesc=4 Link=7".parse().unwrap(),
2905 required: "Desc=5 Cons=5-12 Wombat=15".parse().unwrap(),
2906 }
2907 .check_protocols(&my_protocols);
2908 assert_eq!(
2909 outcome,
2910 Err(ProtocolSupportError::MissingRequired(
2911 "Cons=6-12 Wombat=15".parse().unwrap()
2912 ))
2913 );
2914 }
2915
2916 #[test]
2917 fn serialize_protostatus() {
2918 let ps = ProtoStatuses {
2919 client: ProtoStatus {
2920 recommended: "Link=1-5 LinkAuth=2-5".parse().unwrap(),
2921 required: "Link=5 LinkAuth=3".parse().unwrap(),
2922 },
2923 relay: ProtoStatus {
2924 recommended: "Wombat=20-30 Knish=20-30".parse().unwrap(),
2925 required: "Wombat=20-22 Knish=25-27".parse().unwrap(),
2926 },
2927 };
2928 let json = serde_json::to_string(&ps).unwrap();
2929 let ps2 = serde_json::from_str(json.as_str()).unwrap();
2930 assert_eq!(ps, ps2);
2931
2932 let ps3: ProtoStatuses = serde_json::from_str(
2933 r#"{
2934 "client":{
2935 "required":"Link=5 LinkAuth=3",
2936 "recommended":"Link=1-5 LinkAuth=2-5"
2937 },
2938 "relay":{
2939 "required":"Wombat=20-22 Knish=25-27",
2940 "recommended":"Wombat=20-30 Knish=20-30"
2941 }
2942 }"#,
2943 )
2944 .unwrap();
2945 assert_eq!(ps, ps3);
2946 }
2947
2948 #[test]
2950 fn verify_error_netstatus_vote() -> Result<(), anyhow::Error> {
2951 use VerifyFailed as VF;
2952 use VoteVerifyFailed as VVF;
2953 use vote::NetworkStatusUnverified as UV;
2954
2955 let file = "testdata2/v3-status-votes--1";
2956 let text = fs::read_to_string(file).with_context(|| file.to_owned())?;
2957 let input = ParseInput::new(&text, file);
2958 let doc: UV = parse_netdoc(&input)?;
2959 let trusted = [doc.peek_alleged_authority()];
2960
2961 let edit_body = |f: &dyn Fn(&mut _)| {
2962 let (mut body, sigs) = doc.clone().unwrap_unverified();
2963 f(&mut body);
2964 UV::from_parts(body, sigs)
2965 };
2966
2967 {
2969 let mut doc = doc.clone();
2970 doc.sigs.sigs.directory_signature.signature.fill(0xff);
2971 assert_matches!(
2972 doc.verify(&trusted),
2973 Err(VVF::InvalidSignature(VF::VerifyFailed))
2974 );
2975 }
2976
2977 {
2979 let doc = doc.clone();
2980 assert_matches!(
2981 doc.verify(&[[0x55; _].into()]),
2982 Err(VVF::InvalidSignature(VF::InsufficientTrustedSigners))
2983 );
2984 }
2985
2986 {
2988 let doc = edit_body(&|body| {
2989 body.authority.authority.dir_source.identity.0 = [0x55; _].into();
2990 });
2991 assert_matches!(
2992 doc.verify(&trusted),
2994 Err(VVF::AuthCertWrongAuthority)
2995 );
2996 }
2997
2998 let with_mutated_lifetime = |f: &dyn Fn(&mut Lifetime)| {
3000 let doc = edit_body(&|body| f(&mut body.preamble.lifetime));
3001 assert_matches!(
3002 doc.verify(&trusted),
3004 Err(VVF::AuthCertWrongValidity(_))
3005 );
3006 };
3007 let t_past = parse_rfc3339("1990-01-01T00:02:25Z")?;
3008 let t_future = parse_rfc3339("2010-01-01T00:02:25Z")?;
3009 with_mutated_lifetime(&|lifetime| lifetime.valid_after.0 = t_future);
3010 with_mutated_lifetime(&|lifetime| lifetime.fresh_until.0 = t_past);
3011 with_mutated_lifetime(&|lifetime| lifetime.valid_until.0 = t_past);
3012
3013 {
3015 let mut text = text.clone();
3016 regsub(&mut text, "^dir-key-expires ", "dir-key-expires-SABOTAGED ");
3017 let input = ParseInput::new(&text, file);
3018 let doc: UV = parse_netdoc(&input)?;
3019 assert_matches!(
3020 doc.verify(&trusted),
3022 Err(VVF::AuthCertParseError(..))
3023 );
3024 }
3025
3026 Ok(())
3027 }
3028
3029 #[cfg(feature = "retain-unknown")]
3030 #[allow(clippy::type_complexity)]
3031 pub(super) fn prep_netstatus_verify<UV: NetdocParseable>(
3032 file: &str,
3033 ) -> anyhow::Result<(UV, String, Vec<AuthCert>, Vec<RsaIdentity>, SystemTime)> {
3034 let text = fs::read_to_string(file).with_context(|| file.to_owned())?;
3035 let now = parse_rfc3339("2000-01-01T00:02:25Z")?;
3036
3037 let mut input = ParseInput::new(&text, file);
3038 input.retain_unknown_values();
3039
3040 let doc: UV = parse_netdoc(&input)?;
3041
3042 let certs = {
3043 let file = "testdata2/cached-certs";
3044 let text = fs::read_to_string(file)?;
3045 let input = ParseInput::new(&text, file);
3046 let certs: Vec<AuthCertUnverified> = parse_netdoc_multiple(&input)?;
3047 certs
3048 .into_iter()
3049 .map(|cert| cert.verify_selfcert(now))
3050 .collect::<Result<Vec<AuthCert>, _>>()?
3051 };
3052
3053 let authorities = certs.iter().map(|cert| *cert.fingerprint).collect_vec();
3054
3055 Ok((doc, text, certs, authorities, now))
3056 }
3057
3058 #[cfg(feature = "retain-unknown")]
3071 fn roundtrip_netstatus<UV, V, VE>(
3072 file: &str,
3075 verify: impl FnOnce(UV, &[RsaIdentity], &[AuthCert]) -> Result<TimeRangeBound<V>, VE>,
3076 adjust_now: Duration,
3077 ) -> anyhow::Result<()>
3078 where
3079 UV: NetdocParseable + NetdocParseableUnverified + MungeForRoundtrip,
3080 UV::Signatures: Clone + Debug + NetdocEncodableFields,
3081 VE: Debug + std::error::Error + Send + Sync + 'static,
3082 V: Debug + NetdocEncodable,
3083 {
3084 let (doc, text, certs, authorities, now) = prep_netstatus_verify::<UV>(file)?;
3085
3086 let now = now + adjust_now;
3087
3088 let sigs = doc.inspect_unverified().1.sigs.clone();
3089
3090 let doc = verify(doc, &authorities, &certs)?.if_valid_at(&now)?;
3091
3092 println!("{doc:?}");
3093
3094 let mut enc = NetdocEncoder::new();
3095 doc.encode_unsigned(&mut enc)?;
3096 sigs.encode_fields(&mut enc)?;
3097 let enc = enc.finish()?;
3098
3099 let mut exp: String = text.clone();
3100
3101 regsub(
3103 &mut exp,
3105 r#"^(shared-rand-.*)$"#,
3106 |c: ®ex::Captures| {
3107 let mut s = c[1].to_owned();
3108 regsub(&mut s, r#"="#, "");
3109 s
3110 },
3111 );
3112
3113 regsub(
3116 &mut exp,
3118 r#"^(client|server)-versions (.+)$"#,
3119 |c: ®ex::Captures| -> String {
3120 format!(
3121 "{}-versions {}",
3122 &c[1],
3123 iter_join(",", c[2].split(',').sorted()),
3124 )
3125 },
3126 );
3127
3128 let mut regsub = |re, repl| regsub(&mut exp, re, repl);
3129
3130 regsub(
3132 r#"^((?:client|server)-versions) $"#,
3134 "$1",
3135 );
3136
3137 regsub(
3141 r#"(?x)
3142 ( ^ r\ .* \n ) # ( r ) $1, part before where we want to put m's
3143 ( (?: .* \n )*? ) # (.*? ) $2, the rest, before the m's
3144 ( (?: m\ .* \n )+ ) # ( m+ ) $3, one or more m's
3145 "#,
3146 r#"$1$3$2"#,
3147 );
3148
3149 UV::adjust_exp(&mut exp);
3150
3151 assert_eq_or_diff!(&exp, &enc);
3152
3153 Ok(())
3154 }
3155
3156 trait MungeForRoundtrip {
3157 fn adjust_exp(exp: &mut String);
3159 }
3160
3161 #[cfg(feature = "retain-unknown")]
3165 #[test]
3166 fn roundtrip_netstatus_plain() -> anyhow::Result<()> {
3167 roundtrip_netstatus::<plain::NetworkStatusUnverified, _, _>(
3168 "testdata2/cached-consensus",
3169 plain::NetworkStatusUnverified::verify,
3170 Duration::ZERO,
3171 )
3172 }
3173
3174 impl MungeForRoundtrip for plain::NetworkStatusUnverified {
3175 fn adjust_exp(exp: &mut String) {
3176 let mut regsub = |re, repl| regsub(exp, re, repl);
3177
3178 regsub(
3181 r#"^network-status-version 3$"#,
3182 "network-status-version 3 ns",
3183 );
3184
3185 regsub(
3189 r#"^(r \S+ \S+ \S+) \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"#,
3190 "$1 2000-01-01 00:00:01",
3191 );
3192 }
3193 }
3194
3195 #[cfg(feature = "retain-unknown")]
3196 #[test]
3197 fn roundtrip_netstatus_md() -> anyhow::Result<()> {
3198 roundtrip_netstatus::<md::NetworkStatusUnverified, _, _>(
3199 "testdata2/cached-microdesc-consensus",
3200 md::NetworkStatusUnverified::verify,
3201 Duration::ZERO,
3202 )
3203 }
3204
3205 impl MungeForRoundtrip for md::NetworkStatusUnverified {
3206 fn adjust_exp(exp: &mut String) {
3207 let mut regsub = |re, repl| regsub(exp, re, repl);
3208
3209 regsub(
3215 r#"^(r \S+ \S+) \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"#,
3216 "$1 2000-01-01 00:00:01",
3217 );
3218 }
3219 }
3220
3221 #[cfg(feature = "retain-unknown")]
3222 #[test]
3223 fn roundtrip_netstatus_vote() -> anyhow::Result<()> {
3224 roundtrip_netstatus::<vote::NetworkStatusUnverified, _, _>(
3225 "testdata2/v3-status-votes--1",
3226 |doc, trusted, _| vote::NetworkStatusUnverified::verify(doc, trusted),
3227 Duration::from_secs(20),
3228 )
3229 }
3230
3231 impl MungeForRoundtrip for vote::NetworkStatusUnverified {
3232 fn adjust_exp(exp: &mut String) {
3233 let stats_massage_entry = |e: &str| {
3237 let mut e = e.to_owned();
3238 if e.contains('.') {
3239 regsub(
3240 &mut e,
3241 r#"(?x)^ ( (?:wfu) = [0-9.]*? )( \.? 0+ ) $"#,
3243 "$1",
3244 );
3245 }
3246 e
3247 };
3248
3249 regsub(exp, r#"^stats (.+)$"#, |c: ®ex::Captures| -> String {
3251 format!(
3252 "stats {}",
3253 iter_join(" ", c[1].split(' ').sorted().map(stats_massage_entry)),
3254 )
3255 });
3256
3257 let mut regsub = |re: &_, repl| regsub(exp, re, repl);
3258
3259 regsub(
3261 r#"(?x)
3262 ^ (recommended-relay-protocols\ .*) \n
3263 (recommended-client-protocols\ .*) \n
3264 (required-relay-protocols\ .*) \n
3265 (required-client-protocols\ .*) \n
3266 (known-flags .*)$ \n
3267 "#,
3268 r#"$5
3269$2
3270$1
3271$4
3272$3
3273"#,
3274 );
3275
3276 regsub(
3282 r#"(?x) ^ (voting-delay\ .*) \n
3283 (known-flags\ .*) \n"#,
3284 "$1
3285client-versions
3286server-versions
3287$2
3288",
3289 );
3290
3291 for missing_field in [
3294 "bandwidth-file-headers", "bandwidth-file-digest", "flag-thresholds", ] {
3298 regsub(&format!(r#"^{missing_field} .*\n"#), "");
3299 }
3300 }
3301 }
3302
3303 fn testdata_live(f: &str) -> String {
3304 let var = "TOR_NETDOC_TESTDATA_LIVE_PREFIX";
3308 let prefix = std::env::var_os(var)
3309 .map(|s| s.into_string().expect(var))
3310 .unwrap_or("testdata-live/".into());
3311 format!("{prefix}{f}")
3312 }
3313
3314 #[allow(clippy::unnecessary_wraps)] fn unwrap_unverified_for_test<UV: NetdocParseableUnverified>(
3316 uv: UV,
3317 _ids: &[RsaIdentity],
3318 _certs: &[AuthCert],
3319 ) -> Result<TimeRangeBound<UV::Body>, std::convert::Infallible> {
3320 Ok(TimeRangeBound::new(uv.unwrap_unverified().0, ..))
3321 }
3322
3323 #[cfg(feature = "retain-unknown")]
3324 #[test]
3325 fn roundtrip_live_plain() -> anyhow::Result<()> {
3326 roundtrip_netstatus::<plain::NetworkStatusUnverified, _, _>(
3327 &testdata_live("consensus"),
3328 unwrap_unverified_for_test,
3329 Duration::ZERO,
3330 )
3331 }
3332
3333 #[cfg(feature = "retain-unknown")]
3334 #[test]
3335 fn roundtrip_live_md() -> anyhow::Result<()> {
3336 roundtrip_netstatus::<md::NetworkStatusUnverified, _, _>(
3337 &testdata_live("consensus-microdesc"),
3338 unwrap_unverified_for_test,
3339 Duration::ZERO,
3340 )
3341 }
3342
3343 #[cfg(feature = "retain-unknown")]
3344 #[test]
3345 fn roundtrip_live_vote() -> anyhow::Result<()> {
3346 roundtrip_netstatus::<vote::NetworkStatusUnverified, _, _>(
3347 &testdata_live("authority"),
3348 unwrap_unverified_for_test,
3349 Duration::ZERO,
3350 )
3351 }
3352}