dirauth.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. #!/usr/bin/env python3
  2. import random # For simulation, not cryptography!
  3. import bisect
  4. import math
  5. import nacl.encoding
  6. import nacl.signing
  7. import network
  8. # A relay descriptor is a dict containing:
  9. # epoch: epoch id
  10. # idkey: a public identity key
  11. # onionkey: a public onion key
  12. # addr: a network address
  13. # bw: bandwidth
  14. # flags: relay flags
  15. # vrfkey: a VRF public key (Single-Pass Walking Onions only)
  16. # sig: a signature over the above by the idkey
  17. class RelayDescriptor:
  18. def __init__(self, descdict):
  19. self.descdict = descdict
  20. def __str__(self, withsig = True):
  21. res = "RelayDesc [\n"
  22. for k in ["epoch", "idkey", "onionkey", "addr", "bw", "flags",
  23. "vrfkey", "sig"]:
  24. if k in self.descdict:
  25. if k == "idkey" or k == "onionkey":
  26. res += " " + k + ": " + self.descdict[k].encode(encoder=nacl.encoding.HexEncoder).decode("ascii") + "\n"
  27. elif k == "sig":
  28. if withsig:
  29. res += " " + k + ": " + nacl.encoding.HexEncoder.encode(self.descdict[k]).decode("ascii") + "\n"
  30. else:
  31. res += " " + k + ": " + str(self.descdict[k]) + "\n"
  32. res += "]\n"
  33. return res
  34. def sign(self, signingkey, perfstats):
  35. serialized = self.__str__(False)
  36. signed = signingkey.sign(serialized.encode("ascii"))
  37. perfstats.sigs += 1
  38. self.descdict["sig"] = signed.signature
  39. @staticmethod
  40. def verify(desc, perfstats):
  41. assert(type(desc) is RelayDescriptor)
  42. serialized = desc.__str__(False)
  43. perfstats.verifs += 1
  44. desc.descdict["idkey"].verify(serialized.encode("ascii"), desc.descdict["sig"])
  45. # A SNIP is a dict containing:
  46. # epoch: epoch id
  47. # idkey: a public identity key
  48. # onionkey: a public onion key
  49. # addr: a network address
  50. # flags: relay flags
  51. # vrfkey: a VRF public key (Single-Pass Walking Onions only)
  52. # range: the (lo,hi) values for the index range (lo is inclusive, hi is
  53. # exclusive; that is, x is in the range if lo <= x < hi).
  54. # lo=hi denotes an empty range.
  55. # auth: either a signature from the authorities over the above
  56. # (Threshold signature case) or a Merkle path to the root
  57. # contained in the consensus (Merkle tree case)
  58. #
  59. # Note that the fields of the SNIP are the same as those of the
  60. # RelayDescriptor, except bw and sig are removed, and range and auth are
  61. # added.
  62. class SNIP:
  63. def __init__(self, snipdict):
  64. self.snipdict = snipdict
  65. def __str__(self, withauth = True):
  66. res = "SNIP [\n"
  67. for k in ["epoch", "idkey", "onionkey", "addr", "flags",
  68. "vrfkey", "range", "auth"]:
  69. if k in self.snipdict:
  70. if k == "idkey" or k == "onionkey":
  71. res += " " + k + ": " + self.snipdict[k].encode(encoder=nacl.encoding.HexEncoder).decode("ascii") + "\n"
  72. elif k == "auth":
  73. if withauth:
  74. if network.thenetwork.snipauthmode == \
  75. network.SNIPAuthMode.THRESHSIG:
  76. res += " " + k + ": " + nacl.encoding.HexEncoder.encode(self.snipdict[k]).decode("ascii") + "\n"
  77. else:
  78. raise NotImplementedError("Merkle auth not yet implemented")
  79. else:
  80. res += " " + k + ": " + str(self.snipdict[k]) + "\n"
  81. res += "]\n"
  82. return res
  83. def auth(self, signingkey, perfstats):
  84. if network.thenetwork.snipauthmode == network.SNIPAuthMode.THRESHSIG:
  85. serialized = self.__str__(False)
  86. signed = signingkey.sign(serialized.encode("ascii"))
  87. perfstats.sigs += 1
  88. self.snipdict["auth"] = signed.signature
  89. else:
  90. raise NotImplementedError("Merkle auth not yet implemented")
  91. @staticmethod
  92. def verify(snip, consensus, verifykey, perfstats):
  93. if network.thenetwork.snipauthmode == network.SNIPAuthMode.THRESHSIG:
  94. assert(type(snip) is SNIP and type(consensus) is Consensus)
  95. serialized = snip.__str__(False)
  96. perfstats.verifs += 1
  97. verifykey.verify(serialized.encode("ascii"),
  98. snip.snipdict["auth"])
  99. else:
  100. raise NotImplementedError("Merkle auth not yet implemented")
  101. # A consensus is a dict containing:
  102. # epoch: epoch id
  103. # numrelays: total number of relays
  104. # totbw: total bandwidth of relays
  105. # merkleroot: the root of the SNIP Merkle tree (Merkle tree auth only)
  106. # relays: list of relay descriptors (Vanilla Onion Routing only)
  107. # sigs: list of signatures from the dirauths
  108. class Consensus:
  109. def __init__(self, epoch, relays):
  110. relays = [ d for d in relays if d.descdict['epoch'] == epoch ]
  111. self.consdict = dict()
  112. self.consdict['epoch'] = epoch
  113. self.consdict['numrelays'] = len(relays)
  114. if network.thenetwork.womode == network.WOMode.VANILLA:
  115. self.consdict['totbw'] = sum([ d.descdict['bw'] for d in relays ])
  116. self.consdict['relays'] = relays
  117. else:
  118. self.consdict['totbw'] = 1<<32
  119. def __str__(self, withsigs = True):
  120. res = "Consensus [\n"
  121. for k in ["epoch", "numrelays", "totbw"]:
  122. if k in self.consdict:
  123. res += " " + k + ": " + str(self.consdict[k]) + "\n"
  124. if network.thenetwork.womode == network.WOMode.VANILLA:
  125. for r in self.consdict['relays']:
  126. res += str(r)
  127. if withsigs and ('sigs' in self.consdict):
  128. for s in self.consdict['sigs']:
  129. res += " sig: " + nacl.encoding.HexEncoder.encode(s).decode("ascii") + "\n"
  130. res += "]\n"
  131. return res
  132. def sign(self, signingkey, index, perfstats):
  133. """Use the given signing key to sign the consensus, storing the
  134. result in the sigs list at the given index."""
  135. serialized = self.__str__(False)
  136. signed = signingkey.sign(serialized.encode("ascii"))
  137. perfstats.sigs += 1
  138. if 'sigs' not in self.consdict:
  139. self.consdict['sigs'] = []
  140. if index >= len(self.consdict['sigs']):
  141. self.consdict['sigs'].extend([None] * (index+1-len(self.consdict['sigs'])))
  142. self.consdict['sigs'][index] = signed.signature
  143. @staticmethod
  144. def verify(consensus, verifkeylist, perfstats):
  145. """Use the given list of verification keys to check the
  146. signatures on the consensus. Return the RelayPicker if
  147. successful, or raise an exception otherwise."""
  148. assert(type(consensus) is Consensus)
  149. serialized = consensus.__str__(False)
  150. for i, vk in enumerate(verifkeylist):
  151. perfstats.verifs += 1
  152. vk.verify(serialized.encode("ascii"), consensus.consdict['sigs'][i])
  153. # If we got this far, all is well. Return the RelayPicker.
  154. return RelayPicker.get(consensus)
  155. # An ENDIVE is a dict containing:
  156. # epoch: epoch id
  157. # snips: list of SNIPS (in THRESHSIG mode, these include the auth
  158. # signatures; in MERKLE mode, these do _not_ include auth)
  159. # sigs: list of signatures from the dirauths
  160. class ENDIVE:
  161. def __init__(self, epoch, snips):
  162. snips = [ s for s in snips if s.snipdict['epoch'] == epoch ]
  163. self.enddict = dict()
  164. self.enddict['epoch'] = epoch
  165. self.enddict['snips'] = snips
  166. def __str__(self, withsigs = True):
  167. res = "ENDIVE [\n"
  168. for k in ["epoch"]:
  169. if k in self.enddict:
  170. res += " " + k + ": " + str(self.enddict[k]) + "\n"
  171. for s in self.enddict['snips']:
  172. res += str(s)
  173. if withsigs and ('sigs' in self.enddict):
  174. for s in self.enddict['sigs']:
  175. res += " sig: " + nacl.encoding.HexEncoder.encode(s).decode("ascii") + "\n"
  176. res += "]\n"
  177. return res
  178. def sign(self, signingkey, index, perfstats):
  179. """Use the given signing key to sign the ENDIVE, storing the
  180. result in the sigs list at the given index."""
  181. serialized = self.__str__(False)
  182. signed = signingkey.sign(serialized.encode("ascii"))
  183. perfstats.sigs += 1
  184. if 'sigs' not in self.enddict:
  185. self.enddict['sigs'] = []
  186. if index >= len(self.enddict['sigs']):
  187. self.enddict['sigs'].extend([None] * (index+1-len(self.enddict['sigs'])))
  188. self.enddict['sigs'][index] = signed.signature
  189. @staticmethod
  190. def verify(endive, consensus, verifkeylist, perfstats):
  191. """Use the given list of verification keys to check the
  192. signatures on the ENDIVE and consensus. Return the RelayPicker
  193. if successful, or raise an exception otherwise."""
  194. assert(type(endive) is ENDIVE and type(consensus) is Consensus)
  195. serializedcons = consensus.__str__(False)
  196. for i, vk in enumerate(verifkeylist):
  197. perfstats.verifs += 1
  198. vk.verify(serializedcons.encode("ascii"), consensus.consdict['sigs'][i])
  199. serializedend = endive.__str__(False)
  200. for i, vk in enumerate(verifkeylist):
  201. perfstats.verifs += 1
  202. vk.verify(serializedend.encode("ascii"), endive.enddict['sigs'][i])
  203. # If we got this far, all is well. Return the RelayPicker.
  204. return RelayPicker.get(consensus, endive)
  205. class RelayPicker:
  206. """An instance of this class (which may be a singleton in the
  207. simulation) is returned by the Consensus.verify() and
  208. ENDIVE.verify() methods. It does any necessary precomputation
  209. and/or caching, and exposes a method to select a random bw-weighted
  210. relay, either explicitly specifying a uniform random value, or
  211. letting the choice be done internally."""
  212. # The singleton instance
  213. relaypicker = None
  214. def __init__(self, consensus, endive = None):
  215. self.epoch = consensus.consdict["epoch"]
  216. self.totbw = consensus.consdict["totbw"]
  217. self.consensus = consensus
  218. self.endive = endive
  219. assert(endive is None or endive.enddict["epoch"] == self.epoch)
  220. if network.thenetwork.womode == network.WOMode.VANILLA:
  221. # Create the array of cumulative bandwidth values from a
  222. # consensus. The array (cdf) will have the same length as
  223. # the number of relays in the consensus. cdf[0] = 0, and
  224. # cdf[i] = cdf[i-1] + relay[i-1].bw.
  225. self.cdf = [0]
  226. for r in consensus.consdict['relays']:
  227. self.cdf.append(self.cdf[-1]+r.descdict['bw'])
  228. # Remove the last item, which should be the sum of all the bws
  229. self.cdf.pop()
  230. print('cdf=', self.cdf)
  231. elif network.thenetwork.snipauthmode == \
  232. network.SNIPAuthMode.THRESHSIG:
  233. # Note that clients will call this with endive = None
  234. if self.endive is not None:
  235. self.cdf = [ s.snipdict['range'][0] \
  236. for s in self.endive.enddict['snips'] ]
  237. else:
  238. self.cdf = None
  239. print('cdf=', self.cdf)
  240. else:
  241. raise NotImplementedError("Merkle auth not yet implemented")
  242. @staticmethod
  243. def get(consensus, endive = None):
  244. # Return the singleton instance, if it exists for this epoch
  245. # However, don't use the cached instance if that one has
  246. # endive=None, but we were passed a real ENDIVE
  247. if RelayPicker.relaypicker is not None and \
  248. (RelayPicker.relaypicker.endive is not None or \
  249. endive is None) and \
  250. RelayPicker.relaypicker.epoch == consensus.consdict["epoch"]:
  251. return RelayPicker.relaypicker
  252. # Create it otherwise, storing the result as the singleton
  253. RelayPicker.relaypicker = RelayPicker(consensus, endive)
  254. return RelayPicker.relaypicker
  255. def pick_relay_by_uniform_index(self, idx):
  256. """Pass in a uniform random index random(0,totbw-1) to get a
  257. relay selected weighted by bw."""
  258. if network.thenetwork.womode == network.WOMode.VANILLA:
  259. relays = self.consensus.consdict['relays']
  260. else:
  261. relays = self.endive.enddict['snips']
  262. # Find the rightmost entry less than or equal to idx
  263. i = bisect.bisect_right(self.cdf, idx)
  264. return relays[i-1]
  265. def pick_weighted_relay(self):
  266. """Select a random relay with probability proportional to its bw
  267. weight."""
  268. totbw = self.totbw
  269. if totbw < 1:
  270. raise ValueError("No relays to choose from")
  271. idx = random.randint(0, totbw-1)
  272. return self.pick_relay_by_uniform_index(idx)
  273. class DirAuthNetMsg(network.NetMsg):
  274. """The subclass of NetMsg for messages to and from directory
  275. authorities."""
  276. class DirAuthUploadDescMsg(DirAuthNetMsg):
  277. """The subclass of DirAuthNetMsg for uploading a relay
  278. descriptor."""
  279. def __init__(self, desc):
  280. self.desc = desc
  281. class DirAuthDelDescMsg(DirAuthNetMsg):
  282. """The subclass of DirAuthNetMsg for deleting a relay
  283. descriptor."""
  284. def __init__(self, desc):
  285. self.desc = desc
  286. class DirAuthGetConsensusMsg(DirAuthNetMsg):
  287. """The subclass of DirAuthNetMsg for fetching the consensus."""
  288. class DirAuthConsensusMsg(DirAuthNetMsg):
  289. """The subclass of DirAuthNetMsg for returning the consensus."""
  290. def __init__(self, consensus):
  291. self.consensus = consensus
  292. class DirAuthGetConsensusDiffMsg(DirAuthNetMsg):
  293. """The subclass of DirAuthNetMsg for fetching the consensus, if the
  294. requestor already has the previous consensus."""
  295. class DirAuthConsensusDiffMsg(DirAuthNetMsg):
  296. """The subclass of DirAuthNetMsg for returning the consensus, if the
  297. requestor already has the previous consensus. We don't _actually_
  298. produce the diff at this time; we just charge fewer bytes for this
  299. message."""
  300. def __init__(self, consensus):
  301. self.consensus = consensus
  302. def size(self):
  303. if network.symbolic_byte_counters:
  304. return super().size()
  305. return math.ceil(DirAuthConsensusMsg(self.consensus).size() \
  306. * network.P_Delta)
  307. class DirAuthGetENDIVEMsg(DirAuthNetMsg):
  308. """The subclass of DirAuthNetMsg for fetching the ENDIVE."""
  309. class DirAuthENDIVEMsg(DirAuthNetMsg):
  310. """The subclass of DirAuthNetMsg for returning the ENDIVE."""
  311. def __init__(self, endive):
  312. self.endive = endive
  313. class DirAuthGetENDIVEDiffMsg(DirAuthNetMsg):
  314. """The subclass of DirAuthNetMsg for fetching the ENDIVE, if the
  315. requestor already has the previous ENDIVE."""
  316. class DirAuthENDIVEDiffMsg(DirAuthNetMsg):
  317. """The subclass of DirAuthNetMsg for returning the ENDIVE, if the
  318. requestor already has the previous consensus. We don't _actually_
  319. produce the diff at this time; we just charge fewer bytes for this
  320. message in Merkle mode. In threshold signature mode, we would still
  321. need to download at least the new signatures for every SNIP in the
  322. ENDIVE, so for now, just assume there's no gain from ENDIVE diffs in
  323. threshold signature mode."""
  324. def __init__(self, endive):
  325. self.endive = endive
  326. def size(self):
  327. if network.symbolic_byte_counters:
  328. return super().size()
  329. if network.thenetwork.snipauthmode == \
  330. network.SNIPAuthMode.THRESHSIG:
  331. return DirAuthENDIVEMsg(self.endive).size()
  332. return math.ceil(DirAuthENDIVEMsg(self.endive).size() \
  333. * network.P_Delta)
  334. class DirAuthConnection(network.ClientConnection):
  335. """The subclass of Connection for connections to directory
  336. authorities."""
  337. def __init__(self, peer):
  338. super().__init__(peer)
  339. def uploaddesc(self, desc):
  340. """Upload our RelayDescriptor to the DirAuth."""
  341. self.sendmsg(DirAuthUploadDescMeg(desc))
  342. def getconsensus(self):
  343. self.consensus = None
  344. self.sendmsg(DirAuthGetConsensusMsg())
  345. return self.consensus
  346. def getconsensusdiff(self):
  347. self.consensus = None
  348. self.sendmsg(DirAuthGetConsensusDiffMsg())
  349. return self.consensus
  350. def getendive(self):
  351. self.endive = None
  352. self.sendmsg(DirAuthGetENDIVEMsg())
  353. return self.endive
  354. def getendivediff(self):
  355. self.endive = None
  356. self.sendmsg(DirAuthGetENDIVEDiffMsg())
  357. return self.endive
  358. def receivedfromserver(self, msg):
  359. if isinstance(msg, DirAuthConsensusMsg):
  360. self.consensus = msg.consensus
  361. elif isinstance(msg, DirAuthConsensusDiffMsg):
  362. self.consensus = msg.consensus
  363. elif isinstance(msg, DirAuthENDIVEMsg):
  364. self.endive = msg.endive
  365. elif isinstance(msg, DirAuthENDIVEDiffMsg):
  366. self.endive = msg.endive
  367. else:
  368. raise TypeError('Not a server-originating DirAuthNetMsg', msg)
  369. class DirAuth(network.Server):
  370. """The class representing directory authorities."""
  371. # We simulate the act of computing the consensus by keeping a
  372. # class-static dict that's accessible to all of the dirauths
  373. # This dict is indexed by epoch, and the value is itself a dict
  374. # indexed by the stringified descriptor, with value a pair of (the
  375. # number of dirauths that saw that descriptor, the descriptor
  376. # itself).
  377. uploadeddescs = dict()
  378. consensus = None
  379. endive = None
  380. def __init__(self, me, tot):
  381. """Create a new directory authority. me is the index of which
  382. dirauth this one is (starting from 0), and tot is the total
  383. number of dirauths."""
  384. self.me = me
  385. self.tot = tot
  386. self.name = "Dirauth %d of %d" % (me+1, tot)
  387. self.perfstats = network.PerfStats(network.EntType.DIRAUTH)
  388. self.perfstats.is_bootstrapping = True
  389. # Create the dirauth signature keypair
  390. self.sigkey = nacl.signing.SigningKey.generate()
  391. self.perfstats.keygens += 1
  392. self.netaddr = network.thenetwork.bind(self)
  393. self.perfstats.name = "DirAuth at %s" % self.netaddr
  394. network.thenetwork.setdirauthkey(me, self.sigkey.verify_key)
  395. network.thenetwork.wantepochticks(self, True, True)
  396. def connected(self, client):
  397. """Callback invoked when a client connects to us. This callback
  398. creates the DirAuthConnection that will be passed to the
  399. client."""
  400. # We don't actually need to keep per-connection state at
  401. # dirauths, even in long-lived connections, so this is
  402. # particularly simple.
  403. return DirAuthConnection(self)
  404. def generate_consensus(self, epoch):
  405. """Generate the consensus (and ENDIVE, if using Walking Onions)
  406. for the given epoch, which should be the one after the one
  407. that's currently about to end."""
  408. threshold = int(self.tot/2)+1
  409. consensusdescs = []
  410. for numseen, desc in DirAuth.uploadeddescs[epoch].values():
  411. if numseen >= threshold:
  412. consensusdescs.append(desc)
  413. DirAuth.consensus = Consensus(epoch, consensusdescs)
  414. if network.thenetwork.womode != network.WOMode.VANILLA:
  415. totbw = sum([ d.descdict["bw"] for d in consensusdescs ])
  416. hi = 0
  417. cumbw = 0
  418. snips = []
  419. for d in consensusdescs:
  420. cumbw += d.descdict["bw"]
  421. lo = hi
  422. hi = int((cumbw<<32)/totbw)
  423. snipdict = dict(d.descdict)
  424. del snipdict["bw"]
  425. snipdict["range"] = (lo,hi)
  426. snips.append(SNIP(snipdict))
  427. DirAuth.endive = ENDIVE(epoch, snips)
  428. def epoch_ending(self, epoch):
  429. # Only dirauth 0 actually needs to generate the consensus
  430. # because of the shared class-static state, but everyone has to
  431. # sign it. Note that this code relies on dirauth 0's
  432. # epoch_ending callback being called before any of the other
  433. # dirauths'.
  434. if (epoch+1) not in DirAuth.uploadeddescs:
  435. DirAuth.uploadeddescs[epoch+1] = dict()
  436. if self.me == 0:
  437. self.generate_consensus(epoch+1)
  438. del DirAuth.uploadeddescs[epoch+1]
  439. if network.thenetwork.snipauthmode == \
  440. network.SNIPAuthMode.THRESHSIG:
  441. for s in DirAuth.endive.enddict['snips']:
  442. s.auth(self.sigkey, self.perfstats)
  443. else:
  444. if network.thenetwork.snipauthmode == \
  445. network.SNIPAuthMode.THRESHSIG:
  446. for s in DirAuth.endive.enddict['snips']:
  447. # We're just simulating threshold sigs by having
  448. # only the first dirauth sign, but in reality each
  449. # dirauth would contribute to the signature (at the
  450. # same cost as each one signing), so we'll charge
  451. # their perfstats as well
  452. self.perfstats.sigs += 1
  453. DirAuth.consensus.sign(self.sigkey, self.me, self.perfstats)
  454. if network.thenetwork.womode != network.WOMode.VANILLA:
  455. DirAuth.endive.sign(self.sigkey, self.me, self.perfstats)
  456. def received(self, client, msg):
  457. self.perfstats.bytes_received += msg.size()
  458. if isinstance(msg, DirAuthUploadDescMsg):
  459. # Check the uploaded descriptor for sanity
  460. epoch = msg.desc.descdict['epoch']
  461. if epoch != network.thenetwork.getepoch() + 1:
  462. return
  463. # Store it in the class-static dict
  464. if epoch not in DirAuth.uploadeddescs:
  465. DirAuth.uploadeddescs[epoch] = dict()
  466. descstr = str(msg.desc)
  467. if descstr not in DirAuth.uploadeddescs[epoch]:
  468. DirAuth.uploadeddescs[epoch][descstr] = (1, msg.desc)
  469. else:
  470. DirAuth.uploadeddescs[epoch][descstr] = \
  471. (DirAuth.uploadeddescs[epoch][descstr][0]+1,
  472. DirAuth.uploadeddescs[epoch][descstr][1])
  473. elif isinstance(msg, DirAuthDelDescMsg):
  474. # Check the uploaded descriptor for sanity
  475. epoch = msg.desc.descdict['epoch']
  476. if epoch != network.thenetwork.getepoch() + 1:
  477. return
  478. # Remove it from the class-static dict
  479. if epoch not in DirAuth.uploadeddescs:
  480. return
  481. descstr = str(msg.desc)
  482. if descstr not in DirAuth.uploadeddescs[epoch]:
  483. return
  484. elif DirAuth.uploadeddescs[epoch][descstr][0] == 1:
  485. del DirAuth.uploadeddescs[epoch][descstr]
  486. else:
  487. DirAuth.uploadeddescs[epoch][descstr] = \
  488. (DirAuth.uploadeddescs[epoch][descstr][0]-1,
  489. DirAuth.uploadeddescs[epoch][descstr][1])
  490. elif isinstance(msg, DirAuthGetConsensusMsg):
  491. replymsg = DirAuthConsensusMsg(DirAuth.consensus)
  492. msgsize = replymsg.size()
  493. self.perfstats.bytes_sent += msgsize
  494. client.reply(replymsg)
  495. elif isinstance(msg, DirAuthGetConsensusDiffMsg):
  496. replymsg = DirAuthConsensusDiffMsg(DirAuth.consensus)
  497. msgsize = replymsg.size()
  498. self.perfstats.bytes_sent += msgsize
  499. client.reply(replymsg)
  500. elif isinstance(msg, DirAuthGetENDIVEMsg):
  501. replymsg = DirAuthENDIVEMsg(DirAuth.endive)
  502. msgsize = replymsg.size()
  503. self.perfstats.bytes_sent += msgsize
  504. client.reply(replymsg)
  505. elif isinstance(msg, DirAuthGetENDIVEDiffMsg):
  506. replymsg = DirAuthENDIVEDiffMsg(DirAuth.endive)
  507. msgsize = replymsg.size()
  508. self.perfstats.bytes_sent += msgsize
  509. client.reply(replymsg)
  510. else:
  511. raise TypeError('Not a client-originating DirAuthNetMsg', msg)
  512. def closed(self):
  513. pass
  514. if __name__ == '__main__':
  515. # Start some dirauths
  516. numdirauths = 9
  517. dirauthaddrs = []
  518. for i in range(numdirauths):
  519. dirauth = DirAuth(i, numdirauths)
  520. dirauthaddrs.append(dirauth.netaddr)
  521. for a in dirauthaddrs:
  522. print(a,end=' ')
  523. print()
  524. network.thenetwork.nextepoch()