protover.rs 24 KB

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