shared_random.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287
  1. /* Copyright (c) 2016-2017, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file shared_random.c
  5. *
  6. * \brief Functions and data structure needed to accomplish the shared
  7. * random protocol as defined in proposal #250.
  8. *
  9. * \details
  10. *
  11. * This file implements the dirauth-only commit-and-reveal protocol specified
  12. * by proposal #250. The protocol has two phases (sr_phase_t): the commitment
  13. * phase and the reveal phase (see get_sr_protocol_phase()).
  14. *
  15. * During the protocol, directory authorities keep state in memory (using
  16. * sr_state_t) and in disk (using sr_disk_state_t). The synchronization between
  17. * these two data structures happens in disk_state_update() and
  18. * disk_state_parse().
  19. *
  20. * Here is a rough protocol outline:
  21. *
  22. * 1) In the beginning of the commitment phase, dirauths generate a
  23. * commitment/reveal value for the current protocol run (see
  24. * new_protocol_run() and sr_generate_our_commit()).
  25. *
  26. * 2) During voting, dirauths publish their commits in their votes
  27. * depending on the current phase. Dirauths also include the two
  28. * latest shared random values (SRV) in their votes.
  29. * (see sr_get_string_for_vote())
  30. *
  31. * 3) Upon receiving a commit from a vote, authorities parse it, verify
  32. * it, and attempt to save any new commitment or reveal information in
  33. * their state file (see extract_shared_random_commits() and
  34. * sr_handle_received_commits()). They also parse SRVs from votes to
  35. * decide which SRV should be included in the final consensus (see
  36. * extract_shared_random_srvs()).
  37. *
  38. * 3) After voting is done, we count the SRVs we extracted from the votes,
  39. * to find the one voted by the majority of dirauths which should be
  40. * included in the final consensus (see get_majority_srv_from_votes()).
  41. * If an appropriate SRV is found, it is embedded in the consensus (see
  42. * sr_get_string_for_consensus()).
  43. *
  44. * 4) At the end of the reveal phase, dirauths compute a fresh SRV for the
  45. * day using the active commits (see sr_compute_srv()). This new SRV
  46. * is embedded in the votes as described above.
  47. *
  48. * Some more notes:
  49. *
  50. * - To support rebooting authorities and to avoid double voting, each dirauth
  51. * saves the current state of the protocol on disk so that it can resume
  52. * normally in case of reboot. The disk state (sr_disk_state_t) is managed by
  53. * shared_random_state.c:state_query() and we go to extra lengths to ensure
  54. * that the state is flushed on disk everytime we receive any useful
  55. * information like commits or SRVs.
  56. *
  57. * - When we receive a commit from a vote, we examine it to see if it's useful
  58. * to us and whether it's appropriate to receive it according to the current
  59. * phase of the protocol (see should_keep_commit()). If the commit is useful
  60. * to us, we save it in our disk state using save_commit_to_state(). When we
  61. * receive the reveal information corresponding to a commitment, we verify
  62. * that they indeed match using verify_commit_and_reveal().
  63. *
  64. * - We treat consensuses as the ground truth, so everytime we generate a new
  65. * consensus we update our SR state accordingly even if our local view was
  66. * different (see sr_act_post_consensus()).
  67. *
  68. * - After a consensus has been composed, the SR protocol state gets prepared
  69. * for the next voting session using sr_state_update(). That function takes
  70. * care of housekeeping and also rotates the SRVs and commits in case a new
  71. * protocol run is coming up. We also call sr_state_update() on bootup (in
  72. * sr_state_init()), to prepare the state for the very first voting session.
  73. *
  74. * Terminology:
  75. *
  76. * - "Commitment" is the commitment value of the commit-and-reveal protocol.
  77. *
  78. * - "Reveal" is the reveal value of the commit-and-reveal protocol.
  79. *
  80. * - "Commit" is a struct (sr_commit_t) that contains a commitment value and
  81. * optionally also a corresponding reveal value.
  82. *
  83. * - "SRV" is the Shared Random Value that gets generated as the result of the
  84. * commit-and-reveal protocol.
  85. **/
  86. #define SHARED_RANDOM_PRIVATE
  87. #include "or.h"
  88. #include "shared_random.h"
  89. #include "config.h"
  90. #include "confparse.h"
  91. #include "networkstatus.h"
  92. #include "routerkeys.h"
  93. #include "router.h"
  94. #include "routerlist.h"
  95. #include "shared_random_state.h"
  96. #include "shared_random_client.h"
  97. #include "util.h"
  98. #include "voting_schedule.h"
  99. #include "dirauth/dirvote.h"
  100. #include "dirauth/mode.h"
  101. /* String prefix of shared random values in votes/consensuses. */
  102. static const char previous_srv_str[] = "shared-rand-previous-value";
  103. static const char current_srv_str[] = "shared-rand-current-value";
  104. static const char commit_ns_str[] = "shared-rand-commit";
  105. static const char sr_flag_ns_str[] = "shared-rand-participate";
  106. /* The value of the consensus param AuthDirNumSRVAgreements found in the
  107. * vote. This is set once the consensus creation subsystem requests the
  108. * SRV(s) that should be put in the consensus. We use this value to decide
  109. * if we keep or not an SRV. */
  110. static int32_t num_srv_agreements_from_vote;
  111. /* Return a heap allocated copy of the SRV <b>orig</b>. */
  112. STATIC sr_srv_t *
  113. srv_dup(const sr_srv_t *orig)
  114. {
  115. sr_srv_t *duplicate = NULL;
  116. if (!orig) {
  117. return NULL;
  118. }
  119. duplicate = tor_malloc_zero(sizeof(sr_srv_t));
  120. duplicate->num_reveals = orig->num_reveals;
  121. memcpy(duplicate->value, orig->value, sizeof(duplicate->value));
  122. return duplicate;
  123. }
  124. /* Allocate a new commit object and initializing it with <b>rsa_identity</b>
  125. * that MUST be provided. The digest algorithm is set to the default one
  126. * that is supported. The rest is uninitialized. This never returns NULL. */
  127. static sr_commit_t *
  128. commit_new(const char *rsa_identity)
  129. {
  130. sr_commit_t *commit;
  131. tor_assert(rsa_identity);
  132. commit = tor_malloc_zero(sizeof(*commit));
  133. commit->alg = SR_DIGEST_ALG;
  134. memcpy(commit->rsa_identity, rsa_identity, sizeof(commit->rsa_identity));
  135. base16_encode(commit->rsa_identity_hex, sizeof(commit->rsa_identity_hex),
  136. commit->rsa_identity, sizeof(commit->rsa_identity));
  137. return commit;
  138. }
  139. /* Issue a log message describing <b>commit</b>. */
  140. static void
  141. commit_log(const sr_commit_t *commit)
  142. {
  143. tor_assert(commit);
  144. log_debug(LD_DIR, "SR: Commit from %s", sr_commit_get_rsa_fpr(commit));
  145. log_debug(LD_DIR, "SR: Commit: [TS: %" PRIu64 "] [Encoded: %s]",
  146. commit->commit_ts, commit->encoded_commit);
  147. log_debug(LD_DIR, "SR: Reveal: [TS: %" PRIu64 "] [Encoded: %s]",
  148. commit->reveal_ts, safe_str(commit->encoded_reveal));
  149. }
  150. /* Make sure that the commitment and reveal information in <b>commit</b>
  151. * match. If they match return 0, return -1 otherwise. This function MUST be
  152. * used everytime we receive a new reveal value. Furthermore, the commit
  153. * object MUST have a reveal value and the hash of the reveal value. */
  154. STATIC int
  155. verify_commit_and_reveal(const sr_commit_t *commit)
  156. {
  157. tor_assert(commit);
  158. log_debug(LD_DIR, "SR: Validating commit from authority %s",
  159. sr_commit_get_rsa_fpr(commit));
  160. /* Check that the timestamps match. */
  161. if (commit->commit_ts != commit->reveal_ts) {
  162. log_warn(LD_BUG, "SR: Commit timestamp %" PRIu64 " doesn't match reveal "
  163. "timestamp %" PRIu64, commit->commit_ts,
  164. commit->reveal_ts);
  165. goto invalid;
  166. }
  167. /* Verify that the hashed_reveal received in the COMMIT message, matches
  168. * the reveal we just received. */
  169. {
  170. /* We first hash the reveal we just received. */
  171. char received_hashed_reveal[sizeof(commit->hashed_reveal)];
  172. /* Only sha3-256 is supported. */
  173. if (commit->alg != SR_DIGEST_ALG) {
  174. goto invalid;
  175. }
  176. /* Use the invariant length since the encoded reveal variable has an
  177. * extra byte for the NUL terminated byte. */
  178. if (crypto_digest256(received_hashed_reveal, commit->encoded_reveal,
  179. SR_REVEAL_BASE64_LEN, commit->alg) < 0) {
  180. /* Unable to digest the reveal blob, this is unlikely. */
  181. goto invalid;
  182. }
  183. /* Now compare that with the hashed_reveal we received in COMMIT. */
  184. if (fast_memneq(received_hashed_reveal, commit->hashed_reveal,
  185. sizeof(received_hashed_reveal))) {
  186. log_warn(LD_BUG, "SR: Received reveal value from authority %s "
  187. "doesn't match the commit value.",
  188. sr_commit_get_rsa_fpr(commit));
  189. goto invalid;
  190. }
  191. }
  192. return 0;
  193. invalid:
  194. return -1;
  195. }
  196. /* Return true iff the commit contains an encoded reveal value. */
  197. STATIC int
  198. commit_has_reveal_value(const sr_commit_t *commit)
  199. {
  200. return !tor_mem_is_zero(commit->encoded_reveal,
  201. sizeof(commit->encoded_reveal));
  202. }
  203. /* Parse the encoded commit. The format is:
  204. * base64-encode( TIMESTAMP || H(REVEAL) )
  205. *
  206. * If successfully decoded and parsed, commit is updated and 0 is returned.
  207. * On error, return -1. */
  208. STATIC int
  209. commit_decode(const char *encoded, sr_commit_t *commit)
  210. {
  211. int decoded_len = 0;
  212. size_t offset = 0;
  213. char b64_decoded[SR_COMMIT_LEN];
  214. tor_assert(encoded);
  215. tor_assert(commit);
  216. if (strlen(encoded) > SR_COMMIT_BASE64_LEN) {
  217. /* This means that if we base64 decode successfully the reveiced commit,
  218. * we'll end up with a bigger decoded commit thus unusable. */
  219. goto error;
  220. }
  221. /* Decode our encoded commit. Let's be careful here since _encoded_ is
  222. * coming from the network in a dirauth vote so we expect nothing more
  223. * than the base64 encoded length of a commit. */
  224. decoded_len = base64_decode(b64_decoded, sizeof(b64_decoded),
  225. encoded, strlen(encoded));
  226. if (decoded_len < 0) {
  227. log_warn(LD_BUG, "SR: Commit from authority %s can't be decoded.",
  228. sr_commit_get_rsa_fpr(commit));
  229. goto error;
  230. }
  231. if (decoded_len != SR_COMMIT_LEN) {
  232. log_warn(LD_BUG, "SR: Commit from authority %s decoded length doesn't "
  233. "match the expected length (%d vs %u).",
  234. sr_commit_get_rsa_fpr(commit), decoded_len,
  235. (unsigned)SR_COMMIT_LEN);
  236. goto error;
  237. }
  238. /* First is the timestamp (8 bytes). */
  239. commit->commit_ts = tor_ntohll(get_uint64(b64_decoded));
  240. offset += sizeof(uint64_t);
  241. /* Next is hashed reveal. */
  242. memcpy(commit->hashed_reveal, b64_decoded + offset,
  243. sizeof(commit->hashed_reveal));
  244. /* Copy the base64 blob to the commit. Useful for voting. */
  245. strlcpy(commit->encoded_commit, encoded, sizeof(commit->encoded_commit));
  246. return 0;
  247. error:
  248. return -1;
  249. }
  250. /* Parse the b64 blob at <b>encoded</b> containing reveal information and
  251. * store the information in-place in <b>commit</b>. Return 0 on success else
  252. * a negative value. */
  253. STATIC int
  254. reveal_decode(const char *encoded, sr_commit_t *commit)
  255. {
  256. int decoded_len = 0;
  257. char b64_decoded[SR_REVEAL_LEN];
  258. tor_assert(encoded);
  259. tor_assert(commit);
  260. if (strlen(encoded) > SR_REVEAL_BASE64_LEN) {
  261. /* This means that if we base64 decode successfully the received reveal
  262. * value, we'll end up with a bigger decoded value thus unusable. */
  263. goto error;
  264. }
  265. /* Decode our encoded reveal. Let's be careful here since _encoded_ is
  266. * coming from the network in a dirauth vote so we expect nothing more
  267. * than the base64 encoded length of our reveal. */
  268. decoded_len = base64_decode(b64_decoded, sizeof(b64_decoded),
  269. encoded, strlen(encoded));
  270. if (decoded_len < 0) {
  271. log_warn(LD_BUG, "SR: Reveal from authority %s can't be decoded.",
  272. sr_commit_get_rsa_fpr(commit));
  273. goto error;
  274. }
  275. if (decoded_len != SR_REVEAL_LEN) {
  276. log_warn(LD_BUG, "SR: Reveal from authority %s decoded length is "
  277. "doesn't match the expected length (%d vs %u)",
  278. sr_commit_get_rsa_fpr(commit), decoded_len,
  279. (unsigned)SR_REVEAL_LEN);
  280. goto error;
  281. }
  282. commit->reveal_ts = tor_ntohll(get_uint64(b64_decoded));
  283. /* Copy the last part, the random value. */
  284. memcpy(commit->random_number, b64_decoded + 8,
  285. sizeof(commit->random_number));
  286. /* Also copy the whole message to use during verification */
  287. strlcpy(commit->encoded_reveal, encoded, sizeof(commit->encoded_reveal));
  288. return 0;
  289. error:
  290. return -1;
  291. }
  292. /* Encode a reveal element using a given commit object to dst which is a
  293. * buffer large enough to put the base64-encoded reveal construction. The
  294. * format is as follow:
  295. * REVEAL = base64-encode( TIMESTAMP || H(RN) )
  296. * Return base64 encoded length on success else a negative value.
  297. */
  298. STATIC int
  299. reveal_encode(const sr_commit_t *commit, char *dst, size_t len)
  300. {
  301. int ret;
  302. size_t offset = 0;
  303. char buf[SR_REVEAL_LEN] = {0};
  304. tor_assert(commit);
  305. tor_assert(dst);
  306. set_uint64(buf, tor_htonll(commit->reveal_ts));
  307. offset += sizeof(uint64_t);
  308. memcpy(buf + offset, commit->random_number,
  309. sizeof(commit->random_number));
  310. /* Let's clean the buffer and then b64 encode it. */
  311. memset(dst, 0, len);
  312. ret = base64_encode(dst, len, buf, sizeof(buf), 0);
  313. /* Wipe this buffer because it contains our random value. */
  314. memwipe(buf, 0, sizeof(buf));
  315. return ret;
  316. }
  317. /* Encode the given commit object to dst which is a buffer large enough to
  318. * put the base64-encoded commit. The format is as follow:
  319. * COMMIT = base64-encode( TIMESTAMP || H(H(RN)) )
  320. * Return base64 encoded length on success else a negative value.
  321. */
  322. STATIC int
  323. commit_encode(const sr_commit_t *commit, char *dst, size_t len)
  324. {
  325. size_t offset = 0;
  326. char buf[SR_COMMIT_LEN] = {0};
  327. tor_assert(commit);
  328. tor_assert(dst);
  329. /* First is the timestamp (8 bytes). */
  330. set_uint64(buf, tor_htonll(commit->commit_ts));
  331. offset += sizeof(uint64_t);
  332. /* and then the hashed reveal. */
  333. memcpy(buf + offset, commit->hashed_reveal,
  334. sizeof(commit->hashed_reveal));
  335. /* Clean the buffer and then b64 encode it. */
  336. memset(dst, 0, len);
  337. return base64_encode(dst, len, buf, sizeof(buf), 0);
  338. }
  339. /* Cleanup both our global state and disk state. */
  340. static void
  341. sr_cleanup(void)
  342. {
  343. sr_state_free_all();
  344. }
  345. /* Using <b>commit</b>, return a newly allocated string containing the commit
  346. * information that should be used during SRV calculation. It's the caller
  347. * responsibility to free the memory. Return NULL if this is not a commit to be
  348. * used for SRV calculation. */
  349. static char *
  350. get_srv_element_from_commit(const sr_commit_t *commit)
  351. {
  352. char *element;
  353. tor_assert(commit);
  354. if (!commit_has_reveal_value(commit)) {
  355. return NULL;
  356. }
  357. tor_asprintf(&element, "%s%s", sr_commit_get_rsa_fpr(commit),
  358. commit->encoded_reveal);
  359. return element;
  360. }
  361. /* Return a srv object that is built with the construction:
  362. * SRV = SHA3-256("shared-random" | INT_8(reveal_num) |
  363. * INT_4(version) | HASHED_REVEALS | previous_SRV)
  364. * This function cannot fail. */
  365. static sr_srv_t *
  366. generate_srv(const char *hashed_reveals, uint64_t reveal_num,
  367. const sr_srv_t *previous_srv)
  368. {
  369. char msg[DIGEST256_LEN + SR_SRV_MSG_LEN] = {0};
  370. size_t offset = 0;
  371. sr_srv_t *srv;
  372. tor_assert(hashed_reveals);
  373. /* Add the invariant token. */
  374. memcpy(msg, SR_SRV_TOKEN, SR_SRV_TOKEN_LEN);
  375. offset += SR_SRV_TOKEN_LEN;
  376. set_uint64(msg + offset, tor_htonll(reveal_num));
  377. offset += sizeof(uint64_t);
  378. set_uint32(msg + offset, htonl(SR_PROTO_VERSION));
  379. offset += sizeof(uint32_t);
  380. memcpy(msg + offset, hashed_reveals, DIGEST256_LEN);
  381. offset += DIGEST256_LEN;
  382. if (previous_srv != NULL) {
  383. memcpy(msg + offset, previous_srv->value, sizeof(previous_srv->value));
  384. }
  385. /* Ok we have our message and key for the HMAC computation, allocate our
  386. * srv object and do the last step. */
  387. srv = tor_malloc_zero(sizeof(*srv));
  388. crypto_digest256((char *) srv->value, msg, sizeof(msg), SR_DIGEST_ALG);
  389. srv->num_reveals = reveal_num;
  390. {
  391. /* Debugging. */
  392. char srv_hash_encoded[SR_SRV_VALUE_BASE64_LEN + 1];
  393. sr_srv_encode(srv_hash_encoded, sizeof(srv_hash_encoded), srv);
  394. log_info(LD_DIR, "SR: Generated SRV: %s", srv_hash_encoded);
  395. }
  396. return srv;
  397. }
  398. /* Compare reveal values and return the result. This should exclusively be
  399. * used by smartlist_sort(). */
  400. static int
  401. compare_reveal_(const void **_a, const void **_b)
  402. {
  403. const sr_commit_t *a = *_a, *b = *_b;
  404. return fast_memcmp(a->hashed_reveal, b->hashed_reveal,
  405. sizeof(a->hashed_reveal));
  406. }
  407. /* Given <b>commit</b> give the line that we should place in our votes.
  408. * It's the responsibility of the caller to free the string. */
  409. static char *
  410. get_vote_line_from_commit(const sr_commit_t *commit, sr_phase_t phase)
  411. {
  412. char *vote_line = NULL;
  413. switch (phase) {
  414. case SR_PHASE_COMMIT:
  415. tor_asprintf(&vote_line, "%s %u %s %s %s\n",
  416. commit_ns_str,
  417. SR_PROTO_VERSION,
  418. crypto_digest_algorithm_get_name(commit->alg),
  419. sr_commit_get_rsa_fpr(commit),
  420. commit->encoded_commit);
  421. break;
  422. case SR_PHASE_REVEAL:
  423. {
  424. /* Send a reveal value for this commit if we have one. */
  425. const char *reveal_str = commit->encoded_reveal;
  426. if (tor_mem_is_zero(commit->encoded_reveal,
  427. sizeof(commit->encoded_reveal))) {
  428. reveal_str = "";
  429. }
  430. tor_asprintf(&vote_line, "%s %u %s %s %s %s\n",
  431. commit_ns_str,
  432. SR_PROTO_VERSION,
  433. crypto_digest_algorithm_get_name(commit->alg),
  434. sr_commit_get_rsa_fpr(commit),
  435. commit->encoded_commit, reveal_str);
  436. break;
  437. }
  438. default:
  439. tor_assert(0);
  440. }
  441. log_debug(LD_DIR, "SR: Commit vote line: %s", vote_line);
  442. return vote_line;
  443. }
  444. /* Return a heap allocated string that contains the given <b>srv</b> string
  445. * representation formatted for a networkstatus document using the
  446. * <b>key</b> as the start of the line. This doesn't return NULL. */
  447. static char *
  448. srv_to_ns_string(const sr_srv_t *srv, const char *key)
  449. {
  450. char *srv_str;
  451. char srv_hash_encoded[SR_SRV_VALUE_BASE64_LEN + 1];
  452. tor_assert(srv);
  453. tor_assert(key);
  454. sr_srv_encode(srv_hash_encoded, sizeof(srv_hash_encoded), srv);
  455. tor_asprintf(&srv_str, "%s %" PRIu64 " %s\n", key,
  456. srv->num_reveals, srv_hash_encoded);
  457. log_debug(LD_DIR, "SR: Consensus SRV line: %s", srv_str);
  458. return srv_str;
  459. }
  460. /* Given the previous SRV and the current SRV, return a heap allocated
  461. * string with their data that could be put in a vote or a consensus. Caller
  462. * must free the returned string. Return NULL if no SRVs were provided. */
  463. static char *
  464. get_ns_str_from_sr_values(const sr_srv_t *prev_srv, const sr_srv_t *cur_srv)
  465. {
  466. smartlist_t *chunks = NULL;
  467. char *srv_str;
  468. if (!prev_srv && !cur_srv) {
  469. return NULL;
  470. }
  471. chunks = smartlist_new();
  472. if (prev_srv) {
  473. char *srv_line = srv_to_ns_string(prev_srv, previous_srv_str);
  474. smartlist_add(chunks, srv_line);
  475. }
  476. if (cur_srv) {
  477. char *srv_line = srv_to_ns_string(cur_srv, current_srv_str);
  478. smartlist_add(chunks, srv_line);
  479. }
  480. /* Join the line(s) here in one string to return. */
  481. srv_str = smartlist_join_strings(chunks, "", 0, NULL);
  482. SMARTLIST_FOREACH(chunks, char *, s, tor_free(s));
  483. smartlist_free(chunks);
  484. return srv_str;
  485. }
  486. /* Return 1 iff the two commits have the same commitment values. This
  487. * function does not care about reveal values. */
  488. STATIC int
  489. commitments_are_the_same(const sr_commit_t *commit_one,
  490. const sr_commit_t *commit_two)
  491. {
  492. tor_assert(commit_one);
  493. tor_assert(commit_two);
  494. if (strcmp(commit_one->encoded_commit, commit_two->encoded_commit)) {
  495. return 0;
  496. }
  497. return 1;
  498. }
  499. /* We just received a commit from the vote of authority with
  500. * <b>identity_digest</b>. Return 1 if this commit is authorititative that
  501. * is, it belongs to the authority that voted it. Else return 0 if not. */
  502. STATIC int
  503. commit_is_authoritative(const sr_commit_t *commit,
  504. const char *voter_key)
  505. {
  506. tor_assert(commit);
  507. tor_assert(voter_key);
  508. return fast_memeq(commit->rsa_identity, voter_key,
  509. sizeof(commit->rsa_identity));
  510. }
  511. /* Decide if the newly received <b>commit</b> should be kept depending on
  512. * the current phase and state of the protocol. The <b>voter_key</b> is the
  513. * RSA identity key fingerprint of the authority's vote from which the
  514. * commit comes from. The <b>phase</b> is the phase we should be validating
  515. * the commit for. Return 1 if the commit should be added to our state or 0
  516. * if not. */
  517. STATIC int
  518. should_keep_commit(const sr_commit_t *commit, const char *voter_key,
  519. sr_phase_t phase)
  520. {
  521. const sr_commit_t *saved_commit;
  522. tor_assert(commit);
  523. tor_assert(voter_key);
  524. log_debug(LD_DIR, "SR: Inspecting commit from %s (voter: %s)?",
  525. sr_commit_get_rsa_fpr(commit),
  526. hex_str(voter_key, DIGEST_LEN));
  527. /* For a commit to be considered, it needs to be authoritative (it should
  528. * be the voter's own commit). */
  529. if (!commit_is_authoritative(commit, voter_key)) {
  530. log_debug(LD_DIR, "SR: Ignoring non-authoritative commit.");
  531. goto ignore;
  532. }
  533. /* Let's make sure, for extra safety, that this fingerprint is known to
  534. * us. Even though this comes from a vote, doesn't hurt to be
  535. * extracareful. */
  536. if (trusteddirserver_get_by_v3_auth_digest(commit->rsa_identity) == NULL) {
  537. log_warn(LD_DIR, "SR: Fingerprint %s is not from a recognized "
  538. "authority. Discarding commit.",
  539. escaped(commit->rsa_identity));
  540. goto ignore;
  541. }
  542. /* Check if the authority that voted for <b>commit</b> has already posted
  543. * a commit before. */
  544. saved_commit = sr_state_get_commit(commit->rsa_identity);
  545. switch (phase) {
  546. case SR_PHASE_COMMIT:
  547. /* Already having a commit for an authority so ignore this one. */
  548. if (saved_commit) {
  549. /* Receiving known commits should happen naturally since commit phase
  550. lasts multiple rounds. However if the commitment value changes
  551. during commit phase, it might be a bug so log more loudly. */
  552. if (!commitments_are_the_same(commit, saved_commit)) {
  553. log_info(LD_DIR,
  554. "SR: Received altered commit from %s in commit phase.",
  555. sr_commit_get_rsa_fpr(commit));
  556. } else {
  557. log_debug(LD_DIR, "SR: Ignoring known commit during commit phase.");
  558. }
  559. goto ignore;
  560. }
  561. /* A commit with a reveal value during commitment phase is very wrong. */
  562. if (commit_has_reveal_value(commit)) {
  563. log_warn(LD_DIR, "SR: Commit from authority %s has a reveal value "
  564. "during COMMIT phase. (voter: %s)",
  565. sr_commit_get_rsa_fpr(commit),
  566. hex_str(voter_key, DIGEST_LEN));
  567. goto ignore;
  568. }
  569. break;
  570. case SR_PHASE_REVEAL:
  571. /* We are now in reveal phase. We keep a commit if and only if:
  572. *
  573. * - We have already seen a commit by this auth, AND
  574. * - the saved commit has the same commitment value as this one, AND
  575. * - the saved commit has no reveal information, AND
  576. * - this commit does have reveal information, AND
  577. * - the reveal & commit information are matching.
  578. *
  579. * If all the above are true, then we are interested in this new commit
  580. * for its reveal information. */
  581. if (!saved_commit) {
  582. log_debug(LD_DIR, "SR: Ignoring commit first seen in reveal phase.");
  583. goto ignore;
  584. }
  585. if (!commitments_are_the_same(commit, saved_commit)) {
  586. log_warn(LD_DIR, "SR: Commit from authority %s is different from "
  587. "previous commit in our state (voter: %s)",
  588. sr_commit_get_rsa_fpr(commit),
  589. hex_str(voter_key, DIGEST_LEN));
  590. goto ignore;
  591. }
  592. if (commit_has_reveal_value(saved_commit)) {
  593. log_debug(LD_DIR, "SR: Ignoring commit with known reveal info.");
  594. goto ignore;
  595. }
  596. if (!commit_has_reveal_value(commit)) {
  597. log_debug(LD_DIR, "SR: Ignoring commit without reveal value.");
  598. goto ignore;
  599. }
  600. if (verify_commit_and_reveal(commit) < 0) {
  601. log_warn(LD_BUG, "SR: Commit from authority %s has an invalid "
  602. "reveal value. (voter: %s)",
  603. sr_commit_get_rsa_fpr(commit),
  604. hex_str(voter_key, DIGEST_LEN));
  605. goto ignore;
  606. }
  607. break;
  608. default:
  609. tor_assert(0);
  610. }
  611. return 1;
  612. ignore:
  613. return 0;
  614. }
  615. /* We are in reveal phase and we found a valid and verified <b>commit</b> in
  616. * a vote that contains reveal values that we could use. Update the commit
  617. * we have in our state. Never call this with an unverified commit. */
  618. STATIC void
  619. save_commit_during_reveal_phase(const sr_commit_t *commit)
  620. {
  621. sr_commit_t *saved_commit;
  622. tor_assert(commit);
  623. /* Get the commit from our state. */
  624. saved_commit = sr_state_get_commit(commit->rsa_identity);
  625. tor_assert(saved_commit);
  626. /* Safety net. They can not be different commitments at this point. */
  627. int same_commits = commitments_are_the_same(commit, saved_commit);
  628. tor_assert(same_commits);
  629. /* Copy reveal information to our saved commit. */
  630. sr_state_copy_reveal_info(saved_commit, commit);
  631. }
  632. /* Save <b>commit</b> to our persistent state. Depending on the current
  633. * phase, different actions are taken. Steals reference of <b>commit</b>.
  634. * The commit object MUST be valid and verified before adding it to the
  635. * state. */
  636. STATIC void
  637. save_commit_to_state(sr_commit_t *commit)
  638. {
  639. sr_phase_t phase = sr_state_get_phase();
  640. ASSERT_COMMIT_VALID(commit);
  641. switch (phase) {
  642. case SR_PHASE_COMMIT:
  643. /* During commit phase, just save any new authoritative commit */
  644. sr_state_add_commit(commit);
  645. break;
  646. case SR_PHASE_REVEAL:
  647. save_commit_during_reveal_phase(commit);
  648. sr_commit_free(commit);
  649. break;
  650. default:
  651. tor_assert(0);
  652. }
  653. }
  654. /* Return 1 if we should we keep an SRV voted by <b>n_agreements</b> auths.
  655. * Return 0 if we should ignore it. */
  656. static int
  657. should_keep_srv(int n_agreements)
  658. {
  659. /* Check if the most popular SRV has reached majority. */
  660. int n_voters = get_n_authorities(V3_DIRINFO);
  661. int votes_required_for_majority = (n_voters / 2) + 1;
  662. /* We need at the very least majority to keep a value. */
  663. if (n_agreements < votes_required_for_majority) {
  664. log_notice(LD_DIR, "SR: SRV didn't reach majority [%d/%d]!",
  665. n_agreements, votes_required_for_majority);
  666. return 0;
  667. }
  668. /* When we just computed a new SRV, we need to have super majority in order
  669. * to keep it. */
  670. if (sr_state_srv_is_fresh()) {
  671. /* Check if we have super majority for this new SRV value. */
  672. if (n_agreements < num_srv_agreements_from_vote) {
  673. log_notice(LD_DIR, "SR: New SRV didn't reach agreement [%d/%d]!",
  674. n_agreements, num_srv_agreements_from_vote);
  675. return 0;
  676. }
  677. }
  678. return 1;
  679. }
  680. /* Helper: compare two DIGEST256_LEN digests. */
  681. static int
  682. compare_srvs_(const void **_a, const void **_b)
  683. {
  684. const sr_srv_t *a = *_a, *b = *_b;
  685. return tor_memcmp(a->value, b->value, sizeof(a->value));
  686. }
  687. /* Return the most frequent member of the sorted list of DIGEST256_LEN
  688. * digests in <b>sl</b> with the count of that most frequent element. */
  689. static sr_srv_t *
  690. smartlist_get_most_frequent_srv(const smartlist_t *sl, int *count_out)
  691. {
  692. return smartlist_get_most_frequent_(sl, compare_srvs_, count_out);
  693. }
  694. /** Compare two SRVs. Used in smartlist sorting. */
  695. static int
  696. compare_srv_(const void **_a, const void **_b)
  697. {
  698. const sr_srv_t *a = *_a, *b = *_b;
  699. return fast_memcmp(a->value, b->value,
  700. sizeof(a->value));
  701. }
  702. /* Using a list of <b>votes</b>, return the SRV object from them that has
  703. * been voted by the majority of dirauths. If <b>current</b> is set, we look
  704. * for the current SRV value else the previous one. The returned pointer is
  705. * an object located inside a vote. NULL is returned if no appropriate value
  706. * could be found. */
  707. STATIC sr_srv_t *
  708. get_majority_srv_from_votes(const smartlist_t *votes, int current)
  709. {
  710. int count = 0;
  711. sr_srv_t *most_frequent_srv = NULL;
  712. sr_srv_t *the_srv = NULL;
  713. smartlist_t *srv_list;
  714. tor_assert(votes);
  715. srv_list = smartlist_new();
  716. /* Walk over votes and register any SRVs found. */
  717. SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
  718. sr_srv_t *srv_tmp = NULL;
  719. if (!v->sr_info.participate) {
  720. /* Ignore vote that do not participate. */
  721. continue;
  722. }
  723. /* Do we want previous or current SRV? */
  724. srv_tmp = current ? v->sr_info.current_srv : v->sr_info.previous_srv;
  725. if (!srv_tmp) {
  726. continue;
  727. }
  728. smartlist_add(srv_list, srv_tmp);
  729. } SMARTLIST_FOREACH_END(v);
  730. smartlist_sort(srv_list, compare_srv_);
  731. most_frequent_srv = smartlist_get_most_frequent_srv(srv_list, &count);
  732. if (!most_frequent_srv) {
  733. goto end;
  734. }
  735. /* Was this SRV voted by enough auths for us to keep it? */
  736. if (!should_keep_srv(count)) {
  737. goto end;
  738. }
  739. /* We found an SRV that we can use! Habemus SRV! */
  740. the_srv = most_frequent_srv;
  741. {
  742. /* Debugging */
  743. char encoded[SR_SRV_VALUE_BASE64_LEN + 1];
  744. sr_srv_encode(encoded, sizeof(encoded), the_srv);
  745. log_debug(LD_DIR, "SR: Chosen SRV by majority: %s (%d votes)", encoded,
  746. count);
  747. }
  748. end:
  749. /* We do not free any sr_srv_t values, we don't have the ownership. */
  750. smartlist_free(srv_list);
  751. return the_srv;
  752. }
  753. /* Free a commit object. */
  754. void
  755. sr_commit_free_(sr_commit_t *commit)
  756. {
  757. if (commit == NULL) {
  758. return;
  759. }
  760. /* Make sure we do not leave OUR random number in memory. */
  761. memwipe(commit->random_number, 0, sizeof(commit->random_number));
  762. tor_free(commit);
  763. }
  764. /* Generate the commitment/reveal value for the protocol run starting at
  765. * <b>timestamp</b>. <b>my_rsa_cert</b> is our authority RSA certificate. */
  766. sr_commit_t *
  767. sr_generate_our_commit(time_t timestamp, const authority_cert_t *my_rsa_cert)
  768. {
  769. sr_commit_t *commit = NULL;
  770. char digest[DIGEST_LEN];
  771. tor_assert(my_rsa_cert);
  772. /* Get our RSA identity fingerprint */
  773. if (crypto_pk_get_digest(my_rsa_cert->identity_key, digest) < 0) {
  774. goto error;
  775. }
  776. /* New commit with our identity key. */
  777. commit = commit_new(digest);
  778. /* Generate the reveal random value */
  779. crypto_strongest_rand(commit->random_number,
  780. sizeof(commit->random_number));
  781. commit->commit_ts = commit->reveal_ts = timestamp;
  782. /* Now get the base64 blob that corresponds to our reveal */
  783. if (reveal_encode(commit, commit->encoded_reveal,
  784. sizeof(commit->encoded_reveal)) < 0) {
  785. log_err(LD_DIR, "SR: Unable to encode our reveal value!");
  786. goto error;
  787. }
  788. /* Now let's create the commitment */
  789. tor_assert(commit->alg == SR_DIGEST_ALG);
  790. /* The invariant length is used here since the encoded reveal variable
  791. * has an extra byte added for the NULL terminated byte. */
  792. if (crypto_digest256(commit->hashed_reveal, commit->encoded_reveal,
  793. SR_REVEAL_BASE64_LEN, commit->alg) < 0) {
  794. goto error;
  795. }
  796. /* Now get the base64 blob that corresponds to our commit. */
  797. if (commit_encode(commit, commit->encoded_commit,
  798. sizeof(commit->encoded_commit)) < 0) {
  799. log_err(LD_DIR, "SR: Unable to encode our commit value!");
  800. goto error;
  801. }
  802. log_debug(LD_DIR, "SR: Generated our commitment:");
  803. commit_log(commit);
  804. /* Our commit better be valid :). */
  805. commit->valid = 1;
  806. return commit;
  807. error:
  808. sr_commit_free(commit);
  809. return NULL;
  810. }
  811. /* Compute the shared random value based on the active commits in our state. */
  812. void
  813. sr_compute_srv(void)
  814. {
  815. uint64_t reveal_num = 0;
  816. char *reveals = NULL;
  817. smartlist_t *chunks, *commits;
  818. digestmap_t *state_commits;
  819. /* Computing a shared random value in the commit phase is very wrong. This
  820. * should only happen at the very end of the reveal phase when a new
  821. * protocol run is about to start. */
  822. tor_assert(sr_state_get_phase() == SR_PHASE_REVEAL);
  823. state_commits = sr_state_get_commits();
  824. commits = smartlist_new();
  825. chunks = smartlist_new();
  826. /* We must make a list of commit ordered by authority fingerprint in
  827. * ascending order as specified by proposal 250. */
  828. DIGESTMAP_FOREACH(state_commits, key, sr_commit_t *, c) {
  829. /* Extra safety net, make sure we have valid commit before using it. */
  830. ASSERT_COMMIT_VALID(c);
  831. /* Let's not use a commit from an authority that we don't know. It's
  832. * possible that an authority could be removed during a protocol run so
  833. * that commit value should never be used in the SRV computation. */
  834. if (trusteddirserver_get_by_v3_auth_digest(c->rsa_identity) == NULL) {
  835. log_warn(LD_DIR, "SR: Fingerprint %s is not from a recognized "
  836. "authority. Discarding commit for the SRV computation.",
  837. sr_commit_get_rsa_fpr(c));
  838. continue;
  839. }
  840. /* We consider this commit valid. */
  841. smartlist_add(commits, c);
  842. } DIGESTMAP_FOREACH_END;
  843. smartlist_sort(commits, compare_reveal_);
  844. /* Now for each commit for that sorted list in ascending order, we'll
  845. * build the element for each authority that needs to go into the srv
  846. * computation. */
  847. SMARTLIST_FOREACH_BEGIN(commits, const sr_commit_t *, c) {
  848. char *element = get_srv_element_from_commit(c);
  849. if (element) {
  850. smartlist_add(chunks, element);
  851. reveal_num++;
  852. }
  853. } SMARTLIST_FOREACH_END(c);
  854. smartlist_free(commits);
  855. {
  856. /* Join all reveal values into one giant string that we'll hash so we
  857. * can generated our shared random value. */
  858. sr_srv_t *current_srv;
  859. char hashed_reveals[DIGEST256_LEN];
  860. reveals = smartlist_join_strings(chunks, "", 0, NULL);
  861. SMARTLIST_FOREACH(chunks, char *, s, tor_free(s));
  862. smartlist_free(chunks);
  863. if (crypto_digest256(hashed_reveals, reveals, strlen(reveals),
  864. SR_DIGEST_ALG) < 0) {
  865. goto end;
  866. }
  867. current_srv = generate_srv(hashed_reveals, reveal_num,
  868. sr_state_get_previous_srv());
  869. sr_state_set_current_srv(current_srv);
  870. /* We have a fresh SRV, flag our state. */
  871. sr_state_set_fresh_srv();
  872. }
  873. end:
  874. tor_free(reveals);
  875. }
  876. /* Parse a commit from a vote or from our disk state and return a newly
  877. * allocated commit object. NULL is returned on error.
  878. *
  879. * The commit's data is in <b>args</b> and the order matters very much:
  880. * version, algname, RSA fingerprint, commit value[, reveal value]
  881. */
  882. sr_commit_t *
  883. sr_parse_commit(const smartlist_t *args)
  884. {
  885. uint32_t version;
  886. char *value, digest[DIGEST_LEN];
  887. digest_algorithm_t alg;
  888. const char *rsa_identity_fpr;
  889. sr_commit_t *commit = NULL;
  890. if (smartlist_len(args) < 4) {
  891. goto error;
  892. }
  893. /* First is the version number of the SR protocol which indicates at which
  894. * version that commit was created. */
  895. value = smartlist_get(args, 0);
  896. version = (uint32_t) tor_parse_ulong(value, 10, 1, UINT32_MAX, NULL, NULL);
  897. if (version > SR_PROTO_VERSION) {
  898. log_info(LD_DIR, "SR: Commit version %" PRIu32 " (%s) is not supported.",
  899. version, escaped(value));
  900. goto error;
  901. }
  902. /* Second is the algorithm. */
  903. value = smartlist_get(args, 1);
  904. alg = crypto_digest_algorithm_parse_name(value);
  905. if (alg != SR_DIGEST_ALG) {
  906. log_warn(LD_BUG, "SR: Commit algorithm %s is not recognized.",
  907. escaped(value));
  908. goto error;
  909. }
  910. /* Third argument is the RSA fingerprint of the auth and turn it into a
  911. * digest value. */
  912. rsa_identity_fpr = smartlist_get(args, 2);
  913. if (base16_decode(digest, DIGEST_LEN, rsa_identity_fpr,
  914. HEX_DIGEST_LEN) < 0) {
  915. log_warn(LD_DIR, "SR: RSA fingerprint %s not decodable",
  916. escaped(rsa_identity_fpr));
  917. goto error;
  918. }
  919. /* Allocate commit since we have a valid identity now. */
  920. commit = commit_new(digest);
  921. /* Fourth argument is the commitment value base64-encoded. */
  922. value = smartlist_get(args, 3);
  923. if (commit_decode(value, commit) < 0) {
  924. goto error;
  925. }
  926. /* (Optional) Fifth argument is the revealed value. */
  927. if (smartlist_len(args) > 4) {
  928. value = smartlist_get(args, 4);
  929. if (reveal_decode(value, commit) < 0) {
  930. goto error;
  931. }
  932. }
  933. return commit;
  934. error:
  935. sr_commit_free(commit);
  936. return NULL;
  937. }
  938. /* Called when we are done parsing a vote by <b>voter_key</b> that might
  939. * contain some useful <b>commits</b>. Find if any of them should be kept
  940. * and update our state accordingly. Once done, the list of commitments will
  941. * be empty. */
  942. void
  943. sr_handle_received_commits(smartlist_t *commits, crypto_pk_t *voter_key)
  944. {
  945. char rsa_identity[DIGEST_LEN];
  946. tor_assert(voter_key);
  947. /* It's possible that the vote has _NO_ commits. */
  948. if (commits == NULL) {
  949. return;
  950. }
  951. /* Get the RSA identity fingerprint of this voter */
  952. if (crypto_pk_get_digest(voter_key, rsa_identity) < 0) {
  953. return;
  954. }
  955. SMARTLIST_FOREACH_BEGIN(commits, sr_commit_t *, commit) {
  956. /* We won't need the commit in this list anymore, kept or not. */
  957. SMARTLIST_DEL_CURRENT(commits, commit);
  958. /* Check if this commit is valid and should be stored in our state. */
  959. if (!should_keep_commit(commit, rsa_identity,
  960. sr_state_get_phase())) {
  961. sr_commit_free(commit);
  962. continue;
  963. }
  964. /* Ok, we have a valid commit now that we are about to put in our state.
  965. * so flag it valid from now on. */
  966. commit->valid = 1;
  967. /* Everything lines up: save this commit to state then! */
  968. save_commit_to_state(commit);
  969. } SMARTLIST_FOREACH_END(commit);
  970. }
  971. /* Return a heap-allocated string containing commits that should be put in
  972. * the votes. It's the responsibility of the caller to free the string.
  973. * This always return a valid string, either empty or with line(s). */
  974. char *
  975. sr_get_string_for_vote(void)
  976. {
  977. char *vote_str = NULL;
  978. digestmap_t *state_commits;
  979. smartlist_t *chunks = smartlist_new();
  980. const or_options_t *options = get_options();
  981. /* Are we participating in the protocol? */
  982. if (!options->AuthDirSharedRandomness) {
  983. goto end;
  984. }
  985. log_debug(LD_DIR, "SR: Preparing our vote info:");
  986. /* First line, put in the vote the participation flag. */
  987. {
  988. char *sr_flag_line;
  989. tor_asprintf(&sr_flag_line, "%s\n", sr_flag_ns_str);
  990. smartlist_add(chunks, sr_flag_line);
  991. }
  992. /* In our vote we include every commitment in our permanent state. */
  993. state_commits = sr_state_get_commits();
  994. smartlist_t *state_commit_vote_lines = smartlist_new();
  995. DIGESTMAP_FOREACH(state_commits, key, const sr_commit_t *, commit) {
  996. char *line = get_vote_line_from_commit(commit, sr_state_get_phase());
  997. smartlist_add(state_commit_vote_lines, line);
  998. } DIGESTMAP_FOREACH_END;
  999. /* Sort the commit strings by version (string, not numeric), algorithm,
  1000. * and fingerprint. This makes sure the commit lines in votes are in a
  1001. * recognisable, stable order. */
  1002. smartlist_sort_strings(state_commit_vote_lines);
  1003. /* Now add the sorted list of commits to the vote */
  1004. smartlist_add_all(chunks, state_commit_vote_lines);
  1005. smartlist_free(state_commit_vote_lines);
  1006. /* Add the SRV value(s) if any. */
  1007. {
  1008. char *srv_lines = get_ns_str_from_sr_values(sr_state_get_previous_srv(),
  1009. sr_state_get_current_srv());
  1010. if (srv_lines) {
  1011. smartlist_add(chunks, srv_lines);
  1012. }
  1013. }
  1014. end:
  1015. vote_str = smartlist_join_strings(chunks, "", 0, NULL);
  1016. SMARTLIST_FOREACH(chunks, char *, s, tor_free(s));
  1017. smartlist_free(chunks);
  1018. return vote_str;
  1019. }
  1020. /* Return a heap-allocated string that should be put in the consensus and
  1021. * contains the shared randomness values. It's the responsibility of the
  1022. * caller to free the string. NULL is returned if no SRV(s) available.
  1023. *
  1024. * This is called when a consensus (any flavor) is bring created thus it
  1025. * should NEVER change the state nor the state should be changed in between
  1026. * consensus creation.
  1027. *
  1028. * <b>num_srv_agreements</b> is taken from the votes thus the voted value
  1029. * that should be used.
  1030. * */
  1031. char *
  1032. sr_get_string_for_consensus(const smartlist_t *votes,
  1033. int32_t num_srv_agreements)
  1034. {
  1035. char *srv_str;
  1036. const or_options_t *options = get_options();
  1037. tor_assert(votes);
  1038. /* Not participating, avoid returning anything. */
  1039. if (!options->AuthDirSharedRandomness) {
  1040. log_info(LD_DIR, "SR: Support disabled (AuthDirSharedRandomness %d)",
  1041. options->AuthDirSharedRandomness);
  1042. goto end;
  1043. }
  1044. /* Set the global value of AuthDirNumSRVAgreements found in the votes. */
  1045. num_srv_agreements_from_vote = num_srv_agreements;
  1046. /* Check the votes and figure out if SRVs should be included in the final
  1047. * consensus. */
  1048. sr_srv_t *prev_srv = get_majority_srv_from_votes(votes, 0);
  1049. sr_srv_t *cur_srv = get_majority_srv_from_votes(votes, 1);
  1050. srv_str = get_ns_str_from_sr_values(prev_srv, cur_srv);
  1051. if (!srv_str) {
  1052. goto end;
  1053. }
  1054. return srv_str;
  1055. end:
  1056. return NULL;
  1057. }
  1058. /* We just computed a new <b>consensus</b>. Update our state with the SRVs
  1059. * from the consensus (might be NULL as well). Register the SRVs in our SR
  1060. * state and prepare for the upcoming protocol round. */
  1061. void
  1062. sr_act_post_consensus(const networkstatus_t *consensus)
  1063. {
  1064. const or_options_t *options = get_options();
  1065. /* Don't act if our state hasn't been initialized. We can be called during
  1066. * boot time when loading consensus from disk which is prior to the
  1067. * initialization of the SR subsystem. We also should not be doing
  1068. * anything if we are _not_ a directory authority and if we are a bridge
  1069. * authority. */
  1070. if (!sr_state_is_initialized() || !authdir_mode_v3(options) ||
  1071. authdir_mode_bridge(options)) {
  1072. return;
  1073. }
  1074. /* Set the majority voted SRVs in our state even if both are NULL. It
  1075. * doesn't matter this is what the majority has decided. Obviously, we can
  1076. * only do that if we have a consensus. */
  1077. if (consensus) {
  1078. /* Start by freeing the current SRVs since the SRVs we believed during
  1079. * voting do not really matter. Now that all the votes are in, we use the
  1080. * majority's opinion on which are the active SRVs. */
  1081. sr_state_clean_srvs();
  1082. /* Reset the fresh flag of the SRV so we know that from now on we don't
  1083. * have a new SRV to vote for. We just used the one from the consensus
  1084. * decided by the majority. */
  1085. sr_state_unset_fresh_srv();
  1086. /* Set the SR values from the given consensus. */
  1087. sr_state_set_previous_srv(srv_dup(consensus->sr_info.previous_srv));
  1088. sr_state_set_current_srv(srv_dup(consensus->sr_info.current_srv));
  1089. }
  1090. /* Prepare our state so that it's ready for the next voting period. */
  1091. sr_state_update(voting_schedule_get_next_valid_after_time());
  1092. }
  1093. /* Initialize shared random subsystem. This MUST be called early in the boot
  1094. * process of tor. Return 0 on success else -1 on error. */
  1095. int
  1096. sr_init(int save_to_disk)
  1097. {
  1098. return sr_state_init(save_to_disk, 1);
  1099. }
  1100. /* Save our state to disk and cleanup everything. */
  1101. void
  1102. sr_save_and_cleanup(void)
  1103. {
  1104. sr_state_save();
  1105. sr_cleanup();
  1106. }
  1107. #ifdef TOR_UNIT_TESTS
  1108. /* Set the global value of number of SRV agreements so the test can play
  1109. * along by calling specific functions that don't parse the votes prior for
  1110. * the AuthDirNumSRVAgreements value. */
  1111. void
  1112. set_num_srv_agreements(int32_t value)
  1113. {
  1114. num_srv_agreements_from_vote = value;
  1115. }
  1116. #endif /* defined(TOR_UNIT_TESTS) */