shared_random.c 43 KB

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