user.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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) {
  169. if self.connect(&bucket[i]) {
  170. succeeded.push(bucket[i]);
  171. } else {
  172. failed.push(bucket[i]);
  173. }
  174. }
  175. }
  176. let second_cred = if succeeded.len() < 1 {
  177. if self.secondary_cred.is_some() {
  178. std::mem::replace(&mut self.secondary_cred, None)
  179. } else {
  180. // Get new credential
  181. let cred = get_lox_credential(
  182. &state.net,
  183. &get_open_invitation(&state.net).await,
  184. get_lox_pub(&state.la_pubkeys),
  185. )
  186. .await
  187. .0;
  188. Some(cred)
  189. }
  190. } else {
  191. // If we're able to connect with the primary credential, don't
  192. // keep a secondary one.
  193. None
  194. };
  195. if second_cred.is_some() {
  196. let second_cred = second_cred.as_ref().unwrap();
  197. let (second_bucket, second_reachcred) = get_bucket(&state.net, &second_cred).await;
  198. if self.connect(&second_bucket[0]) {
  199. succeeded.push(second_bucket[0]);
  200. if second_reachcred.is_some()
  201. && eligible_for_trust_promotion(&state.net, &second_cred).await
  202. {
  203. second_level_up = true;
  204. }
  205. } else {
  206. failed.push(second_bucket[0]);
  207. }
  208. }
  209. let mut negative_reports = Vec::<NegativeReport>::new();
  210. let mut positive_reports = Vec::<PositiveReport>::new();
  211. if self.submits_reports {
  212. for bridge in &failed {
  213. negative_reports.push(NegativeReport::from_bridgeline(
  214. *bridge,
  215. self.country.to_string(),
  216. BridgeDistributor::Lox,
  217. ));
  218. }
  219. if level >= 3 {
  220. for bridge in &succeeded {
  221. positive_reports.push(
  222. PositiveReport::from_lox_credential(
  223. bridge.fingerprint,
  224. None,
  225. &self.primary_cred,
  226. get_lox_pub(&state.la_pubkeys),
  227. self.country.to_string(),
  228. )
  229. .unwrap(),
  230. );
  231. }
  232. }
  233. }
  234. // We might restrict these steps to succeeded.len() > 0, but we do
  235. // assume the user can contact the LA somehow, so let's just allow it.
  236. if can_level_up {
  237. let cred = level_up(
  238. &state.net,
  239. &self.primary_cred,
  240. &reachcred.unwrap(),
  241. get_lox_pub(&state.la_pubkeys),
  242. get_reachability_pub(&state.la_pubkeys),
  243. )
  244. .await;
  245. self.primary_cred = cred;
  246. self.secondary_cred = None;
  247. }
  248. // We favor starting over at level 1 to migrating
  249. else if second_level_up {
  250. let second_cred = second_cred.as_ref().unwrap();
  251. let cred = trust_migration(
  252. &state.net,
  253. &second_cred,
  254. &trust_promotion(&state.net, &second_cred, get_lox_pub(&state.la_pubkeys)).await,
  255. get_lox_pub(&state.la_pubkeys),
  256. get_migration_pub(&state.la_pubkeys),
  257. )
  258. .await;
  259. self.primary_cred = cred;
  260. self.secondary_cred = None;
  261. } else if can_migrate {
  262. let cred = blockage_migration(
  263. &state.net,
  264. &self.primary_cred,
  265. &check_blockage(
  266. &state.net,
  267. &self.primary_cred,
  268. get_lox_pub(&state.la_pubkeys),
  269. )
  270. .await,
  271. get_lox_pub(&state.la_pubkeys),
  272. get_migration_pub(&state.la_pubkeys),
  273. )
  274. .await;
  275. self.primary_cred = cred;
  276. self.secondary_cred = None;
  277. } else if second_cred.is_some() {
  278. // Couldn't connect with primary credential
  279. if succeeded.len() > 0 {
  280. // Keep the second credential only if it's useful
  281. self.secondary_cred = second_cred;
  282. }
  283. }
  284. if negative_reports.len() > 0 {
  285. Self::send_negative_reports(&state, negative_reports).await;
  286. }
  287. if positive_reports.len() > 0 {
  288. Self::send_positive_reports(&state, positive_reports).await;
  289. }
  290. // Invite friends if applicable
  291. let invitations = scalar_u32(&self.primary_cred.invites_remaining).unwrap();
  292. let mut new_friends = Vec::<User>::new();
  293. for _i in 0..invitations {
  294. let mut rng = rand::thread_rng();
  295. let num: f64 = rng.gen_range(0.0..1.0);
  296. if num < state.prob_user_invites_friend {
  297. match self.invite(&state).await {
  298. Ok(friend) => {
  299. // You really shouldn't push your friends, especially
  300. // new ones whose boundaries you might not know well.
  301. new_friends.push(friend);
  302. }
  303. Err(e) => {
  304. println!("{}", e);
  305. }
  306. }
  307. }
  308. }
  309. // List of fingerprints we contacted. This should not actually be more
  310. // than one.
  311. let mut connections = Vec::<[u8; 20]>::new();
  312. for bridge in succeeded {
  313. connections.push(bridge.get_hashed_fingerprint());
  314. }
  315. (new_friends, connections)
  316. }
  317. }