shared_random.c 43 KB

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