protover.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. // Copyright (c) 2016-2017, The Tor Project, Inc. */
  2. // See LICENSE for licensing information */
  3. use std::collections::HashMap;
  4. use std::collections::hash_map;
  5. use std::ffi::CStr;
  6. use std::fmt;
  7. use std::str;
  8. use std::str::FromStr;
  9. use std::string::String;
  10. use tor_log::{LogSeverity, LogDomain};
  11. use external::c_tor_version_as_new_as;
  12. use errors::ProtoverError;
  13. use protoset::Version;
  14. use protoset::ProtoSet;
  15. /// The first version of Tor that included "proto" entries in its descriptors.
  16. /// Authorities should use this to decide whether to guess proto lines.
  17. ///
  18. /// C_RUST_COUPLED:
  19. /// src/or/protover.h `FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS`
  20. const FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS: &'static str = "0.2.9.3-alpha";
  21. /// The maximum number of subprotocol version numbers we will attempt to expand
  22. /// before concluding that someone is trying to DoS us
  23. ///
  24. /// C_RUST_COUPLED: src/or/protover.c `MAX_PROTOCOLS_TO_EXPAND`
  25. pub(crate) const MAX_PROTOCOLS_TO_EXPAND: usize = (1<<16);
  26. /// Known subprotocols in Tor. Indicates which subprotocol a relay supports.
  27. ///
  28. /// C_RUST_COUPLED: src/or/protover.h `protocol_type_t`
  29. #[derive(Clone, Hash, Eq, PartialEq, Debug)]
  30. pub enum Protocol {
  31. Cons,
  32. Desc,
  33. DirCache,
  34. HSDir,
  35. HSIntro,
  36. HSRend,
  37. Link,
  38. LinkAuth,
  39. Microdesc,
  40. Relay,
  41. }
  42. impl fmt::Display for Protocol {
  43. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  44. write!(f, "{:?}", self)
  45. }
  46. }
  47. /// Translates a string representation of a protocol into a Proto type.
  48. /// Error if the string is an unrecognized protocol name.
  49. ///
  50. /// C_RUST_COUPLED: src/or/protover.c `PROTOCOL_NAMES`
  51. impl FromStr for Protocol {
  52. type Err = ProtoverError;
  53. fn from_str(s: &str) -> Result<Self, Self::Err> {
  54. match s {
  55. "Cons" => Ok(Protocol::Cons),
  56. "Desc" => Ok(Protocol::Desc),
  57. "DirCache" => Ok(Protocol::DirCache),
  58. "HSDir" => Ok(Protocol::HSDir),
  59. "HSIntro" => Ok(Protocol::HSIntro),
  60. "HSRend" => Ok(Protocol::HSRend),
  61. "Link" => Ok(Protocol::Link),
  62. "LinkAuth" => Ok(Protocol::LinkAuth),
  63. "Microdesc" => Ok(Protocol::Microdesc),
  64. "Relay" => Ok(Protocol::Relay),
  65. _ => Err(ProtoverError::UnknownProtocol),
  66. }
  67. }
  68. }
  69. /// A protocol string which is not one of the `Protocols` we currently know
  70. /// about.
  71. #[derive(Clone, Debug, Hash, Eq, PartialEq)]
  72. pub struct UnknownProtocol(String);
  73. impl fmt::Display for UnknownProtocol {
  74. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  75. write!(f, "{}", self.0)
  76. }
  77. }
  78. impl FromStr for UnknownProtocol {
  79. type Err = ProtoverError;
  80. fn from_str(s: &str) -> Result<Self, Self::Err> {
  81. Ok(UnknownProtocol(s.to_string()))
  82. }
  83. }
  84. impl From<Protocol> for UnknownProtocol {
  85. fn from(p: Protocol) -> UnknownProtocol {
  86. UnknownProtocol(p.to_string())
  87. }
  88. }
  89. /// Get a CStr representation of current supported protocols, for
  90. /// passing to C, or for converting to a `&str` for Rust.
  91. ///
  92. /// # Returns
  93. ///
  94. /// An `&'static CStr` whose value is the existing protocols supported by tor.
  95. /// Returned data is in the format as follows:
  96. ///
  97. /// "HSDir=1-1 LinkAuth=1"
  98. ///
  99. /// # Note
  100. ///
  101. /// Rust code can use the `&'static CStr` as a normal `&'a str` by
  102. /// calling `protover::get_supported_protocols`.
  103. ///
  104. // C_RUST_COUPLED: src/or/protover.c `protover_get_supported_protocols`
  105. pub(crate) fn get_supported_protocols_cstr() -> &'static CStr {
  106. cstr!("Cons=1-2 \
  107. Desc=1-2 \
  108. DirCache=1-2 \
  109. HSDir=1-2 \
  110. HSIntro=3-4 \
  111. HSRend=1-2 \
  112. Link=1-5 \
  113. LinkAuth=1,3 \
  114. Microdesc=1-2 \
  115. Relay=1-2")
  116. }
  117. /// A map of protocol names to the versions of them which are supported.
  118. #[derive(Clone, Debug, PartialEq, Eq)]
  119. pub struct ProtoEntry(HashMap<Protocol, ProtoSet>);
  120. impl Default for ProtoEntry {
  121. fn default() -> ProtoEntry {
  122. ProtoEntry( HashMap::new() )
  123. }
  124. }
  125. impl ProtoEntry {
  126. /// Get an iterator over the `Protocol`s and their `ProtoSet`s in this `ProtoEntry`.
  127. pub fn iter(&self) -> hash_map::Iter<Protocol, ProtoSet> {
  128. self.0.iter()
  129. }
  130. /// Translate the supported tor versions from a string into a
  131. /// ProtoEntry, which is useful when looking up a specific
  132. /// subprotocol.
  133. pub fn supported() -> Result<Self, ProtoverError> {
  134. let supported_cstr: &'static CStr = get_supported_protocols_cstr();
  135. let supported: &str = supported_cstr.to_str().unwrap_or("");
  136. supported.parse()
  137. }
  138. pub fn get(&self, protocol: &Protocol) -> Option<&ProtoSet> {
  139. self.0.get(protocol)
  140. }
  141. pub fn insert(&mut self, key: Protocol, value: ProtoSet) {
  142. self.0.insert(key, value);
  143. }
  144. pub fn remove(&mut self, key: &Protocol) -> Option<ProtoSet> {
  145. self.0.remove(key)
  146. }
  147. pub fn is_empty(&self) -> bool {
  148. self.0.is_empty()
  149. }
  150. }
  151. impl FromStr for ProtoEntry {
  152. type Err = ProtoverError;
  153. /// Parse a string of subprotocol types and their version numbers.
  154. ///
  155. /// # Inputs
  156. ///
  157. /// * A `protocol_entry` string, comprised of a keywords, an "=" sign, and
  158. /// one or more version numbers, each separated by a space. For example,
  159. /// `"Cons=3-4 HSDir=1"`.
  160. ///
  161. /// # Returns
  162. ///
  163. /// A `Result` whose `Ok` value is a `ProtoEntry`, where the
  164. /// first element is the subprotocol type (see `protover::Protocol`) and the last
  165. /// element is an ordered set of `(low, high)` unique version numbers which are supported.
  166. /// Otherwise, the `Err` value of this `Result` is a `ProtoverError`.
  167. fn from_str(protocol_entry: &str) -> Result<ProtoEntry, ProtoverError> {
  168. let mut proto_entry: ProtoEntry = ProtoEntry::default();
  169. let entries = protocol_entry.split(' ');
  170. for entry in entries {
  171. let mut parts = entry.splitn(2, '=');
  172. let proto = match parts.next() {
  173. Some(n) => n,
  174. None => return Err(ProtoverError::Unparseable),
  175. };
  176. let vers = match parts.next() {
  177. Some(n) => n,
  178. None => return Err(ProtoverError::Unparseable),
  179. };
  180. let versions: ProtoSet = vers.parse()?;
  181. let proto_name: Protocol = proto.parse()?;
  182. proto_entry.insert(proto_name, versions);
  183. }
  184. Ok(proto_entry)
  185. }
  186. }
  187. /// Parses a single subprotocol entry string into subprotocol and version
  188. /// parts, and then checks whether any of those versions are unsupported.
  189. /// Helper for protover::all_supported
  190. ///
  191. /// # Inputs
  192. ///
  193. /// Accepted data is in the string format as follows:
  194. ///
  195. /// "HSDir=1-1"
  196. ///
  197. /// # Returns
  198. ///
  199. /// Returns `true` if the protocol entry is well-formatted and only contains
  200. /// versions that are also supported in tor. Otherwise, returns false
  201. ///
  202. fn contains_only_supported_protocols(proto_entry: &str) -> bool {
  203. let (name, mut vers) = match get_proto_and_vers(proto_entry) {
  204. Ok(n) => n,
  205. Err("Too many versions to expand") => {
  206. tor_log_msg!(
  207. LogSeverity::Warn,
  208. LogDomain::Net,
  209. "get_versions",
  210. "When expanding a protocol list from an authority, I \
  211. got too many protocols. This is possibly an attack or a bug, \
  212. unless the Tor network truly has expanded to support over {} \
  213. different subprotocol versions. The offending string was: {}",
  214. MAX_PROTOCOLS_TO_EXPAND,
  215. proto_entry
  216. );
  217. return false;
  218. }
  219. Err(_) => return false,
  220. };
  221. let currently_supported = match SupportedProtocols::tor_supported() {
  222. Ok(n) => n.0,
  223. Err(_) => return false,
  224. };
  225. let supported_versions = match currently_supported.get(&name) {
  226. Some(n) => n,
  227. None => return false,
  228. };
  229. vers.0.retain(|x| !supported_versions.0.contains(x));
  230. vers.0.is_empty()
  231. }
  232. /// Determine if we support every protocol a client supports, and if not,
  233. /// determine which protocols we do not have support for.
  234. ///
  235. /// # Inputs
  236. ///
  237. /// Accepted data is in the string format as follows:
  238. ///
  239. /// "HSDir=1-1 LinkAuth=1-2"
  240. ///
  241. /// # Returns
  242. ///
  243. /// Return `true` if every protocol version is one that we support.
  244. /// Otherwise, return `false`.
  245. /// Optionally, return parameters which the client supports but which we do not
  246. ///
  247. /// # Examples
  248. /// ```
  249. /// use protover::all_supported;
  250. ///
  251. /// let (is_supported, unsupported) = all_supported("Link=1");
  252. /// assert_eq!(true, is_supported);
  253. ///
  254. /// let (is_supported, unsupported) = all_supported("Link=5-6");
  255. /// assert_eq!(false, is_supported);
  256. /// assert_eq!("Link=5-6", unsupported);
  257. ///
  258. pub fn all_supported(protocols: &str) -> (bool, String) {
  259. let unsupported = protocols
  260. .split_whitespace()
  261. .filter(|v| !contains_only_supported_protocols(v))
  262. .collect::<Vec<&str>>();
  263. (unsupported.is_empty(), unsupported.join(" "))
  264. }
  265. /// Return true iff the provided protocol list includes support for the
  266. /// indicated protocol and version.
  267. /// Otherwise, return false
  268. ///
  269. /// # Inputs
  270. ///
  271. /// * `list`, a string representation of a list of protocol entries.
  272. /// * `proto`, a `Proto` to test support for
  273. /// * `vers`, a `Version` version which we will go on to determine whether the
  274. /// specified protocol supports.
  275. ///
  276. /// # Examples
  277. /// ```
  278. /// use protover::*;
  279. ///
  280. /// let is_supported = protover_string_supports_protocol("Link=3-4 Cons=1",
  281. /// Proto::Cons,1);
  282. /// assert_eq!(true, is_supported);
  283. ///
  284. /// let is_not_supported = protover_string_supports_protocol("Link=3-4 Cons=1",
  285. /// Proto::Cons,5);
  286. /// assert_eq!(false, is_not_supported)
  287. /// ```
  288. pub fn protover_string_supports_protocol(
  289. list: &str,
  290. proto: Proto,
  291. vers: Version,
  292. ) -> bool {
  293. let supported = match SupportedProtocols::from_proto_entries_string(list) {
  294. Ok(result) => result.0,
  295. Err(_) => return false,
  296. };
  297. let supported_versions = match supported.get(&proto) {
  298. Some(n) => n,
  299. None => return false,
  300. };
  301. supported_versions.0.contains(&vers)
  302. }
  303. /// As protover_string_supports_protocol(), but also returns True if
  304. /// any later version of the protocol is supported.
  305. ///
  306. /// # Examples
  307. /// ```
  308. /// use protover::*;
  309. ///
  310. /// let is_supported = protover_string_supports_protocol_or_later(
  311. /// "Link=3-4 Cons=5", Proto::Cons, 5);
  312. ///
  313. /// assert_eq!(true, is_supported);
  314. ///
  315. /// let is_supported = protover_string_supports_protocol_or_later(
  316. /// "Link=3-4 Cons=5", Proto::Cons, 4);
  317. ///
  318. /// assert_eq!(true, is_supported);
  319. ///
  320. /// let is_supported = protover_string_supports_protocol_or_later(
  321. /// "Link=3-4 Cons=5", Proto::Cons, 6);
  322. ///
  323. /// assert_eq!(false, is_supported);
  324. /// ```
  325. pub fn protover_string_supports_protocol_or_later(
  326. list: &str,
  327. proto: Proto,
  328. vers: u32,
  329. ) -> bool {
  330. let supported = match SupportedProtocols::from_proto_entries_string(list) {
  331. Ok(result) => result.0,
  332. Err(_) => return false,
  333. };
  334. let supported_versions = match supported.get(&proto) {
  335. Some(n) => n,
  336. None => return false,
  337. };
  338. supported_versions.0.iter().any(|v| v >= &vers)
  339. }
  340. /// Parses a protocol list without validating the protocol names
  341. ///
  342. /// # Inputs
  343. ///
  344. /// * `protocol_string`, a string comprised of keys and values, both which are
  345. /// strings. The keys are the protocol names while values are a string
  346. /// representation of the supported versions.
  347. ///
  348. /// The input is _not_ expected to be a subset of the Proto types
  349. ///
  350. /// # Returns
  351. ///
  352. /// A `Result` whose `Ok` value is a `HashSet<Version>` holding all of the
  353. /// unique version numbers.
  354. ///
  355. /// The returned `Result`'s `Err` value is an `&'static str` with a description
  356. /// of the error.
  357. ///
  358. /// # Errors
  359. ///
  360. /// This function will error if:
  361. ///
  362. /// * The protocol string does not follow the "protocol_name=version_list"
  363. /// expected format
  364. /// * If the version string is malformed. See `Versions::from_version_string`.
  365. ///
  366. fn parse_protocols_from_string_with_no_validation<'a>(
  367. protocol_string: &'a str,
  368. ) -> Result<HashMap<String, Versions>, &'static str> {
  369. let mut parsed: HashMap<String, Versions> = HashMap::new();
  370. for subproto in protocol_string.split(" ") {
  371. let mut parts = subproto.splitn(2, "=");
  372. let name = match parts.next() {
  373. Some("") => return Err("invalid protover entry"),
  374. Some(n) => n,
  375. None => return Err("invalid protover entry"),
  376. };
  377. let vers = match parts.next() {
  378. Some(n) => n,
  379. None => return Err("invalid protover entry"),
  380. };
  381. let versions = Versions::from_version_string(vers)?;
  382. parsed.insert(String::from(name), versions);
  383. }
  384. Ok(parsed)
  385. }
  386. /// Protocol voting implementation.
  387. ///
  388. /// Given a list of strings describing protocol versions, return a new
  389. /// string encoding all of the protocols that are listed by at
  390. /// least threshold of the inputs.
  391. ///
  392. /// The string is sorted according to the following conventions:
  393. /// - Protocols names are alphabetized
  394. /// - Protocols are in order low to high
  395. /// - Individual and ranges are listed together. For example,
  396. /// "3, 5-10,13"
  397. /// - All entries are unique
  398. ///
  399. /// # Examples
  400. /// ```
  401. /// use protover::compute_vote;
  402. ///
  403. /// let protos = vec![String::from("Link=3-4"), String::from("Link=3")];
  404. /// let vote = compute_vote(protos, 2);
  405. /// assert_eq!("Link=3", vote)
  406. /// ```
  407. pub fn compute_vote(
  408. list_of_proto_strings: Vec<String>,
  409. threshold: i32,
  410. ) -> String {
  411. let empty = String::from("");
  412. if list_of_proto_strings.is_empty() {
  413. return empty;
  414. }
  415. // all_count is a structure to represent the count of the number of
  416. // supported versions for a specific protocol. For example, in JSON format:
  417. // {
  418. // "FirstSupportedProtocol": {
  419. // "1": "3",
  420. // "2": "1"
  421. // }
  422. // }
  423. // means that FirstSupportedProtocol has three votes which support version
  424. // 1, and one vote that supports version 2
  425. let mut all_count: HashMap<String, HashMap<Version, usize>> =
  426. HashMap::new();
  427. // parse and collect all of the protos and their versions and collect them
  428. for vote in list_of_proto_strings {
  429. let this_vote: HashMap<String, Versions> =
  430. match parse_protocols_from_string_with_no_validation(&vote) {
  431. Ok(result) => result,
  432. Err(_) => continue,
  433. };
  434. for (protocol, versions) in this_vote {
  435. let supported_vers: &mut HashMap<Version, usize> =
  436. all_count.entry(protocol).or_insert(HashMap::new());
  437. for version in versions.0 {
  438. let counter: &mut usize =
  439. supported_vers.entry(version).or_insert(0);
  440. *counter += 1;
  441. }
  442. }
  443. }
  444. let mut final_output: HashMap<String, String> =
  445. HashMap::with_capacity(get_supported_protocols().split(" ").count());
  446. // Go through and remove verstions that are less than the threshold
  447. for (protocol, versions) in all_count {
  448. let mut meets_threshold = HashSet::new();
  449. for (version, count) in versions {
  450. if count >= threshold as usize {
  451. meets_threshold.insert(version);
  452. }
  453. }
  454. // For each protocol, compress its version list into the expected
  455. // protocol version string format
  456. let contracted = contract_protocol_list(&meets_threshold);
  457. if !contracted.is_empty() {
  458. final_output.insert(protocol, contracted);
  459. }
  460. }
  461. write_vote_to_string(&final_output)
  462. }
  463. /// Return a String comprised of protocol entries in alphabetical order
  464. ///
  465. /// # Inputs
  466. ///
  467. /// * `vote`, a `HashMap` comprised of keys and values, both which are strings.
  468. /// The keys are the protocol names while values are a string representation of
  469. /// the supported versions.
  470. ///
  471. /// # Returns
  472. ///
  473. /// A `String` whose value is series of pairs, comprising of the protocol name
  474. /// and versions that it supports. The string takes the following format:
  475. ///
  476. /// "first_protocol_name=1,2-5, second_protocol_name=4,5"
  477. ///
  478. /// Sorts the keys in alphabetical order and creates the expected subprotocol
  479. /// entry format.
  480. ///
  481. fn write_vote_to_string(vote: &HashMap<String, String>) -> String {
  482. let mut keys: Vec<&String> = vote.keys().collect();
  483. keys.sort();
  484. let mut output = Vec::new();
  485. for key in keys {
  486. // TODO error in indexing here?
  487. output.push(format!("{}={}", key, vote[key]));
  488. }
  489. output.join(" ")
  490. }
  491. /// Returns a boolean indicating whether the given protocol and version is
  492. /// supported in any of the existing Tor protocols
  493. ///
  494. /// # Examples
  495. /// ```
  496. /// use protover::*;
  497. ///
  498. /// let is_supported = is_supported_here(Proto::Link, 10);
  499. /// assert_eq!(false, is_supported);
  500. ///
  501. /// let is_supported = is_supported_here(Proto::Link, 1);
  502. /// assert_eq!(true, is_supported);
  503. /// ```
  504. pub fn is_supported_here(proto: Proto, vers: Version) -> bool {
  505. let currently_supported = match SupportedProtocols::tor_supported() {
  506. Ok(result) => result.0,
  507. Err(_) => return false,
  508. };
  509. let supported_versions = match currently_supported.get(&proto) {
  510. Some(n) => n,
  511. None => return false,
  512. };
  513. supported_versions.0.contains(&vers)
  514. }
  515. /// Older versions of Tor cannot infer their own subprotocols
  516. /// Used to determine which subprotocols are supported by older Tor versions.
  517. ///
  518. /// # Inputs
  519. ///
  520. /// * `version`, a string comprised of "[0-9a-z.-]"
  521. ///
  522. /// # Returns
  523. ///
  524. /// A `&'static CStr` encoding a list of protocol names and supported
  525. /// versions. The string takes the following format:
  526. ///
  527. /// "HSDir=1-1 LinkAuth=1"
  528. ///
  529. /// This function returns the protocols that are supported by the version input,
  530. /// only for tor versions older than FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS.
  531. ///
  532. /// C_RUST_COUPLED: src/rust/protover.c `compute_for_old_tor`
  533. pub fn compute_for_old_tor(version: &str) -> &'static CStr {
  534. let empty: &'static CStr = cstr!("");
  535. if c_tor_version_as_new_as(version, FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS) {
  536. return empty;
  537. }
  538. if c_tor_version_as_new_as(version, "0.2.9.1-alpha") {
  539. return cstr!("Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1-2 \
  540. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2");
  541. }
  542. if c_tor_version_as_new_as(version, "0.2.7.5") {
  543. return cstr!("Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  544. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2");
  545. }
  546. if c_tor_version_as_new_as(version, "0.2.4.19") {
  547. return cstr!("Cons=1 Desc=1 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  548. Link=1-4 LinkAuth=1 Microdesc=1 Relay=1-2");
  549. }
  550. empty
  551. }
  552. #[cfg(test)]
  553. mod test {
  554. use std::str::FromStr;
  555. use std::string::ToString;
  556. use super::*;
  557. #[test]
  558. fn test_versions_from_version_string() {
  559. use std::collections::HashSet;
  560. use super::Versions;
  561. assert_eq!(Err("invalid protocol entry"), Versions::from_version_string("a,b"));
  562. assert_eq!(Err("invalid protocol entry"), Versions::from_version_string("1,!"));
  563. {
  564. let mut versions: HashSet<Version> = HashSet::new();
  565. versions.insert(1);
  566. assert_eq!(versions, Versions::from_version_string("1").unwrap().0);
  567. }
  568. {
  569. let mut versions: HashSet<Version> = HashSet::new();
  570. versions.insert(1);
  571. versions.insert(2);
  572. assert_eq!(versions, Versions::from_version_string("1,2").unwrap().0);
  573. }
  574. {
  575. let mut versions: HashSet<Version> = HashSet::new();
  576. versions.insert(1);
  577. versions.insert(2);
  578. versions.insert(3);
  579. assert_eq!(versions, Versions::from_version_string("1-3").unwrap().0);
  580. }
  581. {
  582. let mut versions: HashSet<Version> = HashSet::new();
  583. versions.insert(1);
  584. versions.insert(2);
  585. versions.insert(5);
  586. assert_eq!(versions, Versions::from_version_string("1-2,5").unwrap().0);
  587. }
  588. {
  589. let mut versions: HashSet<Version> = HashSet::new();
  590. versions.insert(1);
  591. versions.insert(3);
  592. versions.insert(4);
  593. versions.insert(5);
  594. assert_eq!(versions, Versions::from_version_string("1,3-5").unwrap().0);
  595. }
  596. }
  597. #[test]
  598. fn test_contains_only_supported_protocols() {
  599. use super::contains_only_supported_protocols;
  600. assert_eq!(false, contains_only_supported_protocols(""));
  601. assert_eq!(true, contains_only_supported_protocols("Cons="));
  602. assert_eq!(true, contains_only_supported_protocols("Cons=1"));
  603. assert_eq!(false, contains_only_supported_protocols("Cons=0"));
  604. assert_eq!(false, contains_only_supported_protocols("Cons=0-1"));
  605. assert_eq!(false, contains_only_supported_protocols("Cons=5"));
  606. assert_eq!(false, contains_only_supported_protocols("Cons=1-5"));
  607. assert_eq!(false, contains_only_supported_protocols("Cons=1,5"));
  608. assert_eq!(false, contains_only_supported_protocols("Cons=5,6"));
  609. assert_eq!(false, contains_only_supported_protocols("Cons=1,5,6"));
  610. assert_eq!(true, contains_only_supported_protocols("Cons=1,2"));
  611. assert_eq!(true, contains_only_supported_protocols("Cons=1-2"));
  612. }
  613. #[test]
  614. fn test_find_range() {
  615. use super::find_range;
  616. assert_eq!((false, 0), find_range(&vec![]));
  617. assert_eq!((false, 1), find_range(&vec![1]));
  618. assert_eq!((true, 2), find_range(&vec![1, 2]));
  619. assert_eq!((true, 3), find_range(&vec![1, 2, 3]));
  620. assert_eq!((true, 3), find_range(&vec![1, 2, 3, 5]));
  621. }
  622. #[test]
  623. fn test_expand_version_range() {
  624. use super::expand_version_range;
  625. assert_eq!(Err("version string empty"), expand_version_range(""));
  626. assert_eq!(Ok(1..3), expand_version_range("1-2"));
  627. assert_eq!(Ok(1..5), expand_version_range("1-4"));
  628. assert_eq!(
  629. Err("cannot parse protocol range lower bound"),
  630. expand_version_range("a")
  631. );
  632. assert_eq!(
  633. Err("cannot parse protocol range upper bound"),
  634. expand_version_range("1-a")
  635. );
  636. assert_eq!(Ok(1000..66536), expand_version_range("1000-66535"));
  637. assert_eq!(Err("Too many protocols in expanded range"),
  638. expand_version_range("1000-66536"));
  639. }
  640. #[test]
  641. fn test_contract_protocol_list() {
  642. use std::collections::HashSet;
  643. use super::contract_protocol_list;
  644. {
  645. let mut versions = HashSet::<Version>::new();
  646. assert_eq!(String::from(""), contract_protocol_list(&versions));
  647. versions.insert(1);
  648. assert_eq!(String::from("1"), contract_protocol_list(&versions));
  649. versions.insert(2);
  650. assert_eq!(String::from("1-2"), contract_protocol_list(&versions));
  651. }
  652. {
  653. let mut versions = HashSet::<Version>::new();
  654. versions.insert(1);
  655. versions.insert(3);
  656. assert_eq!(String::from("1,3"), contract_protocol_list(&versions));
  657. }
  658. {
  659. let mut versions = HashSet::<Version>::new();
  660. versions.insert(1);
  661. versions.insert(2);
  662. versions.insert(3);
  663. versions.insert(4);
  664. assert_eq!(String::from("1-4"), contract_protocol_list(&versions));
  665. }
  666. {
  667. let mut versions = HashSet::<Version>::new();
  668. versions.insert(1);
  669. versions.insert(3);
  670. versions.insert(5);
  671. versions.insert(6);
  672. versions.insert(7);
  673. assert_eq!(
  674. String::from("1,3,5-7"),
  675. contract_protocol_list(&versions)
  676. );
  677. }
  678. {
  679. let mut versions = HashSet::<Version>::new();
  680. versions.insert(1);
  681. versions.insert(2);
  682. versions.insert(3);
  683. versions.insert(500);
  684. assert_eq!(
  685. String::from("1-3,500"),
  686. contract_protocol_list(&versions)
  687. );
  688. }
  689. }
  690. }