user.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. // User behavior in simulation
  2. use crate::{
  3. get_date, negative_report::NegativeReport, positive_report::PositiveReport,
  4. simulation::state::State, BridgeDistributor,
  5. };
  6. use lox_cli::{networking::*, *};
  7. use lox_library::{
  8. bridge_table::BridgeLine, cred::Lox, proto::check_blockage::MIN_TRUST_LEVEL, scalar_u32,
  9. };
  10. use rand::Rng;
  11. pub struct User {
  12. // Does this user cooperate with a censor?
  13. censor: bool,
  14. // 2-character country code
  15. country: String,
  16. // The user always has a primary credential. If this credential's bucket is
  17. // blocked, the user may replace it or temporarily hold two credentials
  18. // while waiting to migrate from the primary credential.
  19. primary_cred: Lox,
  20. secondary_cred: Option<Lox>,
  21. // Does the user submit reports to Troll Patrol?
  22. submits_reports: bool,
  23. }
  24. impl User {
  25. pub async fn new(state: &State) -> Self {
  26. let cred = get_lox_credential(
  27. &state.net,
  28. &get_open_invitation(&state.net).await,
  29. get_lox_pub(&state.la_pubkeys),
  30. )
  31. .await
  32. .0;
  33. // Probabilistically decide whether this user cooperates with a censor
  34. let mut rng = rand::thread_rng();
  35. let num: f64 = rng.gen_range(0.0..1.0);
  36. let censor = num < state.prob_user_is_censor;
  37. // Probabilistically decide whether this user submits reports
  38. let num: f64 = rng.gen_range(0.0..1.0);
  39. let submits_reports = num < state.prob_user_submits_reports;
  40. // Probabilistically decide user's country
  41. let mut num: f64 = rng.gen_range(0.0..1.0);
  42. let cc = {
  43. let mut cc = String::default();
  44. for (country, prob) in &state.probs_user_in_country {
  45. let prob = *prob;
  46. if prob < num {
  47. cc = country.to_string();
  48. break;
  49. } else {
  50. num -= prob;
  51. }
  52. }
  53. cc
  54. };
  55. Self {
  56. censor: censor,
  57. country: cc,
  58. primary_cred: cred,
  59. secondary_cred: None,
  60. submits_reports: submits_reports,
  61. }
  62. }
  63. // TODO: This should probably return an actual error type
  64. pub async fn invite(&mut self, state: &State) -> Result<Self, String> {
  65. let etable = get_reachability_credential(&state.net).await;
  66. let (new_cred, invite) = issue_invite(
  67. &state.net,
  68. &self.primary_cred,
  69. &etable,
  70. get_lox_pub(&state.la_pubkeys),
  71. get_reachability_pub(&state.la_pubkeys),
  72. get_invitation_pub(&state.la_pubkeys),
  73. )
  74. .await;
  75. self.primary_cred = new_cred;
  76. let friend_cred = redeem_invite(
  77. &state.net,
  78. &invite,
  79. get_lox_pub(&state.la_pubkeys),
  80. get_invitation_pub(&state.la_pubkeys),
  81. )
  82. .await
  83. .0;
  84. // Probabilistically decide whether this user cooperates with a censor
  85. // We do not influence this by the inviting friend's status. Anyone
  86. // might have friends who are untrustworthy, and censors may invite
  87. // non-censors to maintain an illusion of trustworthiness. Also, a
  88. // "censor" user may not be knowingly helping a censor.
  89. let mut rng = rand::thread_rng();
  90. let num: f64 = rng.gen_range(0.0..1.0);
  91. let censor = num < state.prob_user_is_censor;
  92. // Probabilistically decide whether this user submits reports
  93. let num: f64 = rng.gen_range(0.0..1.0);
  94. let submits_reports = num < state.prob_user_submits_reports;
  95. // Determine user's country
  96. let num: f64 = rng.gen_range(0.0..1.0);
  97. let cc = if num < state.prob_friend_in_same_country {
  98. self.country.to_string()
  99. } else {
  100. // Probabilistically decide user's country
  101. let mut num: f64 = rng.gen_range(0.0..1.0);
  102. let mut cc = String::default();
  103. for (country, prob) in &state.probs_user_in_country {
  104. let prob = *prob;
  105. if prob < num {
  106. cc = country.to_string();
  107. break;
  108. } else {
  109. num -= prob;
  110. }
  111. }
  112. cc
  113. };
  114. Ok(Self {
  115. censor: censor,
  116. country: cc,
  117. primary_cred: friend_cred,
  118. secondary_cred: None,
  119. submits_reports: submits_reports,
  120. })
  121. }
  122. // Attempt to "connect" to the bridge, returns true if successful
  123. pub fn connect(&self, bridge: &BridgeLine) -> bool {
  124. true
  125. }
  126. pub async fn send_negative_reports(state: &State, reports: Vec<NegativeReport>) {
  127. let date = get_date();
  128. let pubkey = state.tp_pubkeys.get(&date).unwrap();
  129. for report in reports {
  130. state
  131. .net_tp
  132. .request(
  133. "/negativereport".to_string(),
  134. bincode::serialize(&report.encrypt(&pubkey)).unwrap(),
  135. )
  136. .await;
  137. }
  138. }
  139. pub async fn send_positive_reports(state: &State, reports: Vec<PositiveReport>) {
  140. for report in reports {
  141. state
  142. .net_tp
  143. .request("/positivereport".to_string(), report.to_json().into_bytes())
  144. .await;
  145. }
  146. }
  147. // User performs daily connection attempts, etc. and returns a vector of
  148. // newly invited friends and a vector of fingerprints of successfully
  149. // contacted bridges.
  150. pub async fn daily_tasks(&mut self, state: &State) -> (Vec<User>, Vec<[u8; 20]>) {
  151. // Download bucket to see if bridge is still reachable
  152. // (We assume that this step can be done even if the user can't actually
  153. // talk to the LA.)
  154. let (bucket, reachcred) = get_bucket(&state.net, &self.primary_cred).await;
  155. let level = scalar_u32(&self.primary_cred.trust_level).unwrap();
  156. // Can we level up the main credential?
  157. let can_level_up = reachcred.is_some()
  158. && (level == 0 && eligible_for_trust_promotion(&state.net, &self.primary_cred).await
  159. || level > 0 && eligible_for_level_up(&state.net, &self.primary_cred).await);
  160. // Can we migrate the main credential?
  161. let can_migrate = reachcred.is_none() && level >= MIN_TRUST_LEVEL;
  162. // Can we level up the secondary credential?
  163. let mut second_level_up = false;
  164. let mut failed = Vec::<BridgeLine>::new();
  165. let mut succeeded = Vec::<BridgeLine>::new();
  166. for i in 0..bucket.len() {
  167. // At level 0, we only have 1 bridge
  168. if (level > 0 || i == 0) && self.connect(&bucket[i]) {
  169. if self.submits_reports && level >= 3 {
  170. succeeded.push(bucket[i]);
  171. }
  172. } else {
  173. if self.submits_reports {
  174. failed.push(bucket[i]);
  175. }
  176. }
  177. }
  178. let second_cred = if succeeded.len() < 1 {
  179. if self.secondary_cred.is_some() {
  180. std::mem::replace(&mut self.secondary_cred, None)
  181. } else {
  182. // Get new credential
  183. let cred = get_lox_credential(
  184. &state.net,
  185. &get_open_invitation(&state.net).await,
  186. get_lox_pub(&state.la_pubkeys),
  187. )
  188. .await
  189. .0;
  190. Some(cred)
  191. }
  192. } else {
  193. // If we're able to connect with the primary credential, don't
  194. // keep a secondary one.
  195. None
  196. };
  197. if second_cred.is_some() {
  198. let second_cred = second_cred.as_ref().unwrap();
  199. let (second_bucket, second_reachcred) = get_bucket(&state.net, &second_cred).await;
  200. if self.connect(&second_bucket[0]) {
  201. succeeded.push(second_bucket[0]);
  202. if second_reachcred.is_some()
  203. && eligible_for_trust_promotion(&state.net, &second_cred).await
  204. {
  205. second_level_up = true;
  206. }
  207. } else {
  208. failed.push(second_bucket[0]);
  209. }
  210. }
  211. let mut negative_reports = Vec::<NegativeReport>::new();
  212. let mut positive_reports = Vec::<PositiveReport>::new();
  213. if self.submits_reports {
  214. for bridge in &failed {
  215. negative_reports.push(NegativeReport::from_bridgeline(
  216. *bridge,
  217. self.country.to_string(),
  218. BridgeDistributor::Lox,
  219. ));
  220. }
  221. if level >= 3 {
  222. for bridge in &succeeded {
  223. positive_reports.push(
  224. PositiveReport::from_lox_credential(
  225. bridge.fingerprint,
  226. None,
  227. &self.primary_cred,
  228. get_lox_pub(&state.la_pubkeys),
  229. self.country.to_string(),
  230. )
  231. .unwrap(),
  232. );
  233. }
  234. }
  235. }
  236. // We might restrict these steps to succeeded.len() > 0, but we do
  237. // assume the user can contact the LA somehow, so let's just allow it.
  238. if can_level_up {
  239. let cred = level_up(
  240. &state.net,
  241. &self.primary_cred,
  242. &reachcred.unwrap(),
  243. get_lox_pub(&state.la_pubkeys),
  244. get_reachability_pub(&state.la_pubkeys),
  245. )
  246. .await;
  247. self.primary_cred = cred;
  248. self.secondary_cred = None;
  249. }
  250. // We favor starting over at level 1 to migrating
  251. else if second_level_up {
  252. let second_cred = second_cred.as_ref().unwrap();
  253. let cred = trust_migration(
  254. &state.net,
  255. &second_cred,
  256. &trust_promotion(&state.net, &second_cred, get_lox_pub(&state.la_pubkeys)).await,
  257. get_lox_pub(&state.la_pubkeys),
  258. get_migration_pub(&state.la_pubkeys),
  259. )
  260. .await;
  261. self.primary_cred = cred;
  262. self.secondary_cred = None;
  263. } else if can_migrate {
  264. let cred = blockage_migration(
  265. &state.net,
  266. &self.primary_cred,
  267. &check_blockage(
  268. &state.net,
  269. &self.primary_cred,
  270. get_lox_pub(&state.la_pubkeys),
  271. )
  272. .await,
  273. get_lox_pub(&state.la_pubkeys),
  274. get_migration_pub(&state.la_pubkeys),
  275. )
  276. .await;
  277. self.primary_cred = cred;
  278. self.secondary_cred = None;
  279. } else if second_cred.is_some() {
  280. // Couldn't connect with primary credential
  281. if succeeded.len() > 0 {
  282. // Keep the second credential only if it's useful
  283. self.secondary_cred = second_cred;
  284. }
  285. }
  286. if negative_reports.len() > 0 {
  287. Self::send_negative_reports(&state, negative_reports).await;
  288. }
  289. if positive_reports.len() > 0 {
  290. Self::send_positive_reports(&state, positive_reports).await;
  291. }
  292. // Invite friends if applicable
  293. let invitations = scalar_u32(&self.primary_cred.invites_remaining).unwrap();
  294. let mut new_friends = Vec::<User>::new();
  295. for _i in 0..invitations {
  296. let mut rng = rand::thread_rng();
  297. let num: f64 = rng.gen_range(0.0..1.0);
  298. if num < state.prob_user_invites_friend {
  299. match self.invite(&state).await {
  300. Ok(friend) => {
  301. // You really shouldn't push your friends, especially
  302. // new ones whose boundaries you might not know well.
  303. new_friends.push(friend);
  304. }
  305. Err(e) => {
  306. println!("{}", e);
  307. }
  308. }
  309. }
  310. }
  311. // List of fingerprints we contacted. This should not actually be more
  312. // than one.
  313. let mut connections = Vec::<[u8; 20]>::new();
  314. for bridge in succeeded {
  315. connections.push(bridge.get_hashed_fingerprint());
  316. }
  317. (new_friends, connections)
  318. }
  319. }