protover.rs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. // Copyright (c) 2016-2017, The Tor Project, Inc. */
  2. // See LICENSE for licensing information */
  3. use external::c_tor_version_as_new_as;
  4. use std::str;
  5. use std::str::FromStr;
  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_util::strings::NUL_BYTE;
  12. use errors::ProtoverError;
  13. use protoset::Version;
  14. /// The first version of Tor that included "proto" entries in its descriptors.
  15. /// Authorities should use this to decide whether to guess proto lines.
  16. ///
  17. /// C_RUST_COUPLED:
  18. /// src/or/protover.h `FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS`
  19. const FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS: &'static str = "0.2.9.3-alpha";
  20. /// The maximum number of subprotocol version numbers we will attempt to expand
  21. /// before concluding that someone is trying to DoS us
  22. ///
  23. /// C_RUST_COUPLED: src/or/protover.c `MAX_PROTOCOLS_TO_EXPAND`
  24. pub(crate) const MAX_PROTOCOLS_TO_EXPAND: usize = (1<<16);
  25. /// Currently supported protocols and their versions, as a byte-slice.
  26. ///
  27. /// # Warning
  28. ///
  29. /// This byte-slice ends in a NUL byte. This is so that we can directly convert
  30. /// it to an `&'static CStr` in the FFI code, in order to hand the static string
  31. /// to C in a way that is compatible with C static strings.
  32. ///
  33. /// Rust code which wishes to accesses this string should use
  34. /// `protover::get_supported_protocols()` instead.
  35. ///
  36. /// C_RUST_COUPLED: src/or/protover.c `protover_get_supported_protocols`
  37. pub(crate) const SUPPORTED_PROTOCOLS: &'static [u8] =
  38. b"Cons=1-2 \
  39. Desc=1-2 \
  40. DirCache=1-2 \
  41. HSDir=1-2 \
  42. HSIntro=3-4 \
  43. HSRend=1-2 \
  44. Link=1-5 \
  45. LinkAuth=1,3 \
  46. Microdesc=1-2 \
  47. Relay=1-2\0";
  48. /// Known subprotocols in Tor. Indicates which subprotocol a relay supports.
  49. ///
  50. /// C_RUST_COUPLED: src/or/protover.h `protocol_type_t`
  51. #[derive(Clone, Hash, Eq, PartialEq, Debug)]
  52. pub enum Protocol {
  53. Cons,
  54. Desc,
  55. DirCache,
  56. HSDir,
  57. HSIntro,
  58. HSRend,
  59. Link,
  60. LinkAuth,
  61. Microdesc,
  62. Relay,
  63. }
  64. impl fmt::Display for Protocol {
  65. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  66. write!(f, "{:?}", self)
  67. }
  68. }
  69. /// Translates a string representation of a protocol into a Proto type.
  70. /// Error if the string is an unrecognized protocol name.
  71. ///
  72. /// C_RUST_COUPLED: src/or/protover.c `PROTOCOL_NAMES`
  73. impl FromStr for Protocol {
  74. type Err = ProtoverError;
  75. fn from_str(s: &str) -> Result<Self, Self::Err> {
  76. match s {
  77. "Cons" => Ok(Protocol::Cons),
  78. "Desc" => Ok(Protocol::Desc),
  79. "DirCache" => Ok(Protocol::DirCache),
  80. "HSDir" => Ok(Protocol::HSDir),
  81. "HSIntro" => Ok(Protocol::HSIntro),
  82. "HSRend" => Ok(Protocol::HSRend),
  83. "Link" => Ok(Protocol::Link),
  84. "LinkAuth" => Ok(Protocol::LinkAuth),
  85. "Microdesc" => Ok(Protocol::Microdesc),
  86. "Relay" => Ok(Protocol::Relay),
  87. _ => Err(ProtoverError::UnknownProtocol),
  88. }
  89. }
  90. }
  91. /// A protocol string which is not one of the `Protocols` we currently know
  92. /// about.
  93. #[derive(Clone, Debug, Hash, Eq, PartialEq)]
  94. pub struct UnknownProtocol(String);
  95. impl fmt::Display for UnknownProtocol {
  96. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  97. write!(f, "{}", self.0)
  98. }
  99. }
  100. impl FromStr for UnknownProtocol {
  101. type Err = ProtoverError;
  102. fn from_str(s: &str) -> Result<Self, Self::Err> {
  103. Ok(UnknownProtocol(s.to_string()))
  104. }
  105. }
  106. impl From<Protocol> for UnknownProtocol {
  107. fn from(p: Protocol) -> UnknownProtocol {
  108. UnknownProtocol(p.to_string())
  109. }
  110. }
  111. /// Get the string representation of current supported protocols
  112. ///
  113. /// # Returns
  114. ///
  115. /// A `String` whose value is the existing protocols supported by tor.
  116. /// Returned data is in the format as follows:
  117. ///
  118. /// "HSDir=1-1 LinkAuth=1"
  119. ///
  120. pub fn get_supported_protocols() -> &'static str {
  121. // The `len() - 1` is to remove the NUL byte.
  122. // The `unwrap` is safe becauase we SUPPORTED_PROTOCOLS is under
  123. // our control.
  124. str::from_utf8(&SUPPORTED_PROTOCOLS[..SUPPORTED_PROTOCOLS.len() - 1])
  125. .unwrap_or("")
  126. }
  127. pub struct SupportedProtocols(HashMap<Proto, Versions>);
  128. impl SupportedProtocols {
  129. pub fn from_proto_entries<I, S>(protocol_strs: I) -> Result<Self, &'static str>
  130. where
  131. I: Iterator<Item = S>,
  132. S: AsRef<str>,
  133. {
  134. let mut parsed = HashMap::new();
  135. for subproto in protocol_strs {
  136. let (name, version) = get_proto_and_vers(subproto.as_ref())?;
  137. parsed.insert(name, version);
  138. }
  139. Ok(SupportedProtocols(parsed))
  140. }
  141. /// Translates a string representation of a protocol list to a
  142. /// SupportedProtocols instance.
  143. ///
  144. /// # Examples
  145. ///
  146. /// ```
  147. /// use protover::SupportedProtocols;
  148. ///
  149. /// let supported_protocols = SupportedProtocols::from_proto_entries_string(
  150. /// "HSDir=1-2 HSIntro=3-4"
  151. /// );
  152. /// ```
  153. pub fn from_proto_entries_string(
  154. proto_entries: &str,
  155. ) -> Result<Self, &'static str> {
  156. Self::from_proto_entries(proto_entries.split(" "))
  157. }
  158. /// Translate the supported tor versions from a string into a
  159. /// HashMap, which is useful when looking up a specific
  160. /// subprotocol.
  161. ///
  162. fn tor_supported() -> Result<Self, &'static str> {
  163. Self::from_proto_entries_string(get_supported_protocols())
  164. }
  165. }
  166. /// Parse the subprotocol type and its version numbers.
  167. ///
  168. /// # Inputs
  169. ///
  170. /// * A `protocol_entry` string, comprised of a keyword, an "=" sign, and one
  171. /// or more version numbers.
  172. ///
  173. /// # Returns
  174. ///
  175. /// A `Result` whose `Ok` value is a tuple of `(Proto, HashSet<u32>)`, where the
  176. /// first element is the subprotocol type (see `protover::Proto`) and the last
  177. /// element is a(n unordered) set of unique version numbers which are supported.
  178. /// Otherwise, the `Err` value of this `Result` is a description of the error
  179. ///
  180. fn get_proto_and_vers<'a>(
  181. protocol_entry: &'a str,
  182. ) -> Result<(Proto, Versions), &'static str> {
  183. let mut parts = protocol_entry.splitn(2, "=");
  184. let proto = match parts.next() {
  185. Some(n) => n,
  186. None => return Err("invalid protover entry"),
  187. };
  188. let vers = match parts.next() {
  189. Some(n) => n,
  190. None => return Err("invalid protover entry"),
  191. };
  192. let versions = Versions::from_version_string(vers)?;
  193. let proto_name = proto.parse()?;
  194. Ok((proto_name, versions))
  195. }
  196. /// Parses a single subprotocol entry string into subprotocol and version
  197. /// parts, and then checks whether any of those versions are unsupported.
  198. /// Helper for protover::all_supported
  199. ///
  200. /// # Inputs
  201. ///
  202. /// Accepted data is in the string format as follows:
  203. ///
  204. /// "HSDir=1-1"
  205. ///
  206. /// # Returns
  207. ///
  208. /// Returns `true` if the protocol entry is well-formatted and only contains
  209. /// versions that are also supported in tor. Otherwise, returns false
  210. ///
  211. fn contains_only_supported_protocols(proto_entry: &str) -> bool {
  212. let (name, mut vers) = match get_proto_and_vers(proto_entry) {
  213. Ok(n) => n,
  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 [u8]` 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 [u8] {
  529. if c_tor_version_as_new_as(version, FIRST_TOR_VERSION_TO_ADVERTISE_PROTOCOLS) {
  530. return NUL_BYTE;
  531. }
  532. if c_tor_version_as_new_as(version, "0.2.9.1-alpha") {
  533. return b"Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1-2 \
  534. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2\0";
  535. }
  536. if c_tor_version_as_new_as(version, "0.2.7.5") {
  537. return b"Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  538. Link=1-4 LinkAuth=1 Microdesc=1-2 Relay=1-2\0";
  539. }
  540. if c_tor_version_as_new_as(version, "0.2.4.19") {
  541. return b"Cons=1 Desc=1 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 \
  542. Link=1-4 LinkAuth=1 Microdesc=1 Relay=1-2\0";
  543. }
  544. NUL_BYTE
  545. }
  546. #[cfg(test)]
  547. mod test {
  548. use std::str::FromStr;
  549. use std::string::ToString;
  550. use super::*;
  551. #[test]
  552. fn test_versions_from_version_string() {
  553. use std::collections::HashSet;
  554. use super::Versions;
  555. assert_eq!(Err("invalid protocol entry"), Versions::from_version_string("a,b"));
  556. assert_eq!(Err("invalid protocol entry"), Versions::from_version_string("1,!"));
  557. {
  558. let mut versions: HashSet<Version> = HashSet::new();
  559. versions.insert(1);
  560. assert_eq!(versions, Versions::from_version_string("1").unwrap().0);
  561. }
  562. {
  563. let mut versions: HashSet<Version> = HashSet::new();
  564. versions.insert(1);
  565. versions.insert(2);
  566. assert_eq!(versions, Versions::from_version_string("1,2").unwrap().0);
  567. }
  568. {
  569. let mut versions: HashSet<Version> = HashSet::new();
  570. versions.insert(1);
  571. versions.insert(2);
  572. versions.insert(3);
  573. assert_eq!(versions, Versions::from_version_string("1-3").unwrap().0);
  574. }
  575. {
  576. let mut versions: HashSet<Version> = HashSet::new();
  577. versions.insert(1);
  578. versions.insert(2);
  579. versions.insert(5);
  580. assert_eq!(versions, Versions::from_version_string("1-2,5").unwrap().0);
  581. }
  582. {
  583. let mut versions: HashSet<Version> = HashSet::new();
  584. versions.insert(1);
  585. versions.insert(3);
  586. versions.insert(4);
  587. versions.insert(5);
  588. assert_eq!(versions, Versions::from_version_string("1,3-5").unwrap().0);
  589. }
  590. }
  591. #[test]
  592. fn test_contains_only_supported_protocols() {
  593. use super::contains_only_supported_protocols;
  594. assert_eq!(false, contains_only_supported_protocols(""));
  595. assert_eq!(true, contains_only_supported_protocols("Cons="));
  596. assert_eq!(true, contains_only_supported_protocols("Cons=1"));
  597. assert_eq!(false, contains_only_supported_protocols("Cons=0"));
  598. assert_eq!(false, contains_only_supported_protocols("Cons=0-1"));
  599. assert_eq!(false, contains_only_supported_protocols("Cons=5"));
  600. assert_eq!(false, contains_only_supported_protocols("Cons=1-5"));
  601. assert_eq!(false, contains_only_supported_protocols("Cons=1,5"));
  602. assert_eq!(false, contains_only_supported_protocols("Cons=5,6"));
  603. assert_eq!(false, contains_only_supported_protocols("Cons=1,5,6"));
  604. assert_eq!(true, contains_only_supported_protocols("Cons=1,2"));
  605. assert_eq!(true, contains_only_supported_protocols("Cons=1-2"));
  606. }
  607. #[test]
  608. fn test_find_range() {
  609. use super::find_range;
  610. assert_eq!((false, 0), find_range(&vec![]));
  611. assert_eq!((false, 1), find_range(&vec![1]));
  612. assert_eq!((true, 2), find_range(&vec![1, 2]));
  613. assert_eq!((true, 3), find_range(&vec![1, 2, 3]));
  614. assert_eq!((true, 3), find_range(&vec![1, 2, 3, 5]));
  615. }
  616. #[test]
  617. fn test_expand_version_range() {
  618. use super::expand_version_range;
  619. assert_eq!(Err("version string empty"), expand_version_range(""));
  620. assert_eq!(Ok(1..3), expand_version_range("1-2"));
  621. assert_eq!(Ok(1..5), expand_version_range("1-4"));
  622. assert_eq!(
  623. Err("cannot parse protocol range lower bound"),
  624. expand_version_range("a")
  625. );
  626. assert_eq!(
  627. Err("cannot parse protocol range upper bound"),
  628. expand_version_range("1-a")
  629. );
  630. assert_eq!(Ok(1000..66536), expand_version_range("1000-66535"));
  631. assert_eq!(Err("Too many protocols in expanded range"),
  632. expand_version_range("1000-66536"));
  633. }
  634. #[test]
  635. fn test_contract_protocol_list() {
  636. use std::collections::HashSet;
  637. use super::contract_protocol_list;
  638. {
  639. let mut versions = HashSet::<Version>::new();
  640. assert_eq!(String::from(""), contract_protocol_list(&versions));
  641. versions.insert(1);
  642. assert_eq!(String::from("1"), contract_protocol_list(&versions));
  643. versions.insert(2);
  644. assert_eq!(String::from("1-2"), contract_protocol_list(&versions));
  645. }
  646. {
  647. let mut versions = HashSet::<Version>::new();
  648. versions.insert(1);
  649. versions.insert(3);
  650. assert_eq!(String::from("1,3"), contract_protocol_list(&versions));
  651. }
  652. {
  653. let mut versions = HashSet::<Version>::new();
  654. versions.insert(1);
  655. versions.insert(2);
  656. versions.insert(3);
  657. versions.insert(4);
  658. assert_eq!(String::from("1-4"), contract_protocol_list(&versions));
  659. }
  660. {
  661. let mut versions = HashSet::<Version>::new();
  662. versions.insert(1);
  663. versions.insert(3);
  664. versions.insert(5);
  665. versions.insert(6);
  666. versions.insert(7);
  667. assert_eq!(
  668. String::from("1,3,5-7"),
  669. contract_protocol_list(&versions)
  670. );
  671. }
  672. {
  673. let mut versions = HashSet::<Version>::new();
  674. versions.insert(1);
  675. versions.insert(2);
  676. versions.insert(3);
  677. versions.insert(500);
  678. assert_eq!(
  679. String::from("1-3,500"),
  680. contract_protocol_list(&versions)
  681. );
  682. }
  683. }
  684. }