user.rs 13 KB

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