dirauth.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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. idx = self.pick_weighted_relay_index()
  269. return self.pick_relay_by_uniform_index(idx)
  270. def pick_weighted_relay_index(self):
  271. """Select a random relay index (for use in Walking Onions)
  272. uniformly, which will results in picking a relay with
  273. probability proportional to its bw weight."""
  274. totbw = self.totbw
  275. if totbw < 1:
  276. raise ValueError("No relays to choose from")
  277. return random.randint(0, totbw-1)
  278. class DirAuthNetMsg(network.NetMsg):
  279. """The subclass of NetMsg for messages to and from directory
  280. authorities."""
  281. class DirAuthUploadDescMsg(DirAuthNetMsg):
  282. """The subclass of DirAuthNetMsg for uploading a relay
  283. descriptor."""
  284. def __init__(self, desc):
  285. self.desc = desc
  286. class DirAuthDelDescMsg(DirAuthNetMsg):
  287. """The subclass of DirAuthNetMsg for deleting a relay
  288. descriptor."""
  289. def __init__(self, desc):
  290. self.desc = desc
  291. class DirAuthGetConsensusMsg(DirAuthNetMsg):
  292. """The subclass of DirAuthNetMsg for fetching the consensus."""
  293. class DirAuthConsensusMsg(DirAuthNetMsg):
  294. """The subclass of DirAuthNetMsg for returning the consensus."""
  295. def __init__(self, consensus):
  296. self.consensus = consensus
  297. class DirAuthGetConsensusDiffMsg(DirAuthNetMsg):
  298. """The subclass of DirAuthNetMsg for fetching the consensus, if the
  299. requestor already has the previous consensus."""
  300. class DirAuthConsensusDiffMsg(DirAuthNetMsg):
  301. """The subclass of DirAuthNetMsg for returning the consensus, if the
  302. requestor already has the previous consensus. We don't _actually_
  303. produce the diff at this time; we just charge fewer bytes for this
  304. message."""
  305. def __init__(self, consensus):
  306. self.consensus = consensus
  307. def size(self):
  308. if network.symbolic_byte_counters:
  309. return super().size()
  310. return math.ceil(DirAuthConsensusMsg(self.consensus).size() \
  311. * network.P_Delta)
  312. class DirAuthGetENDIVEMsg(DirAuthNetMsg):
  313. """The subclass of DirAuthNetMsg for fetching the ENDIVE."""
  314. class DirAuthENDIVEMsg(DirAuthNetMsg):
  315. """The subclass of DirAuthNetMsg for returning the ENDIVE."""
  316. def __init__(self, endive):
  317. self.endive = endive
  318. class DirAuthGetENDIVEDiffMsg(DirAuthNetMsg):
  319. """The subclass of DirAuthNetMsg for fetching the ENDIVE, if the
  320. requestor already has the previous ENDIVE."""
  321. class DirAuthENDIVEDiffMsg(DirAuthNetMsg):
  322. """The subclass of DirAuthNetMsg for returning the ENDIVE, if the
  323. requestor already has the previous consensus. We don't _actually_
  324. produce the diff at this time; we just charge fewer bytes for this
  325. message in Merkle mode. In threshold signature mode, we would still
  326. need to download at least the new signatures for every SNIP in the
  327. ENDIVE, so for now, just assume there's no gain from ENDIVE diffs in
  328. threshold signature mode."""
  329. def __init__(self, endive):
  330. self.endive = endive
  331. def size(self):
  332. if network.symbolic_byte_counters:
  333. return super().size()
  334. if network.thenetwork.snipauthmode == \
  335. network.SNIPAuthMode.THRESHSIG:
  336. return DirAuthENDIVEMsg(self.endive).size()
  337. return math.ceil(DirAuthENDIVEMsg(self.endive).size() \
  338. * network.P_Delta)
  339. class DirAuthConnection(network.ClientConnection):
  340. """The subclass of Connection for connections to directory
  341. authorities."""
  342. def __init__(self, peer):
  343. super().__init__(peer)
  344. def uploaddesc(self, desc):
  345. """Upload our RelayDescriptor to the DirAuth."""
  346. self.sendmsg(DirAuthUploadDescMeg(desc))
  347. def getconsensus(self):
  348. self.consensus = None
  349. self.sendmsg(DirAuthGetConsensusMsg())
  350. return self.consensus
  351. def getconsensusdiff(self):
  352. self.consensus = None
  353. self.sendmsg(DirAuthGetConsensusDiffMsg())
  354. return self.consensus
  355. def getendive(self):
  356. self.endive = None
  357. self.sendmsg(DirAuthGetENDIVEMsg())
  358. return self.endive
  359. def getendivediff(self):
  360. self.endive = None
  361. self.sendmsg(DirAuthGetENDIVEDiffMsg())
  362. return self.endive
  363. def receivedfromserver(self, msg):
  364. if isinstance(msg, DirAuthConsensusMsg):
  365. self.consensus = msg.consensus
  366. elif isinstance(msg, DirAuthConsensusDiffMsg):
  367. self.consensus = msg.consensus
  368. elif isinstance(msg, DirAuthENDIVEMsg):
  369. self.endive = msg.endive
  370. elif isinstance(msg, DirAuthENDIVEDiffMsg):
  371. self.endive = msg.endive
  372. else:
  373. raise TypeError('Not a server-originating DirAuthNetMsg', msg)
  374. class DirAuth(network.Server):
  375. """The class representing directory authorities."""
  376. # We simulate the act of computing the consensus by keeping a
  377. # class-static dict that's accessible to all of the dirauths
  378. # This dict is indexed by epoch, and the value is itself a dict
  379. # indexed by the stringified descriptor, with value a pair of (the
  380. # number of dirauths that saw that descriptor, the descriptor
  381. # itself).
  382. uploadeddescs = dict()
  383. consensus = None
  384. endive = None
  385. def __init__(self, me, tot):
  386. """Create a new directory authority. me is the index of which
  387. dirauth this one is (starting from 0), and tot is the total
  388. number of dirauths."""
  389. self.me = me
  390. self.tot = tot
  391. self.name = "Dirauth %d of %d" % (me+1, tot)
  392. self.perfstats = network.PerfStats(network.EntType.DIRAUTH)
  393. self.perfstats.is_bootstrapping = True
  394. # Create the dirauth signature keypair
  395. self.sigkey = nacl.signing.SigningKey.generate()
  396. self.perfstats.keygens += 1
  397. self.netaddr = network.thenetwork.bind(self)
  398. self.perfstats.name = "DirAuth at %s" % self.netaddr
  399. network.thenetwork.setdirauthkey(me, self.sigkey.verify_key)
  400. network.thenetwork.wantepochticks(self, True, True)
  401. def connected(self, client):
  402. """Callback invoked when a client connects to us. This callback
  403. creates the DirAuthConnection that will be passed to the
  404. client."""
  405. # We don't actually need to keep per-connection state at
  406. # dirauths, even in long-lived connections, so this is
  407. # particularly simple.
  408. return DirAuthConnection(self)
  409. def generate_consensus(self, epoch):
  410. """Generate the consensus (and ENDIVE, if using Walking Onions)
  411. for the given epoch, which should be the one after the one
  412. that's currently about to end."""
  413. threshold = int(self.tot/2)+1
  414. consensusdescs = []
  415. for numseen, desc in DirAuth.uploadeddescs[epoch].values():
  416. if numseen >= threshold:
  417. consensusdescs.append(desc)
  418. DirAuth.consensus = Consensus(epoch, consensusdescs)
  419. if network.thenetwork.womode != network.WOMode.VANILLA:
  420. totbw = sum([ d.descdict["bw"] for d in consensusdescs ])
  421. hi = 0
  422. cumbw = 0
  423. snips = []
  424. for d in consensusdescs:
  425. cumbw += d.descdict["bw"]
  426. lo = hi
  427. hi = int((cumbw<<32)/totbw)
  428. snipdict = dict(d.descdict)
  429. del snipdict["bw"]
  430. snipdict["range"] = (lo,hi)
  431. snips.append(SNIP(snipdict))
  432. DirAuth.endive = ENDIVE(epoch, snips)
  433. def epoch_ending(self, epoch):
  434. # Only dirauth 0 actually needs to generate the consensus
  435. # because of the shared class-static state, but everyone has to
  436. # sign it. Note that this code relies on dirauth 0's
  437. # epoch_ending callback being called before any of the other
  438. # dirauths'.
  439. if (epoch+1) not in DirAuth.uploadeddescs:
  440. DirAuth.uploadeddescs[epoch+1] = dict()
  441. if self.me == 0:
  442. self.generate_consensus(epoch+1)
  443. del DirAuth.uploadeddescs[epoch+1]
  444. if network.thenetwork.snipauthmode == \
  445. network.SNIPAuthMode.THRESHSIG:
  446. for s in DirAuth.endive.enddict['snips']:
  447. s.auth(self.sigkey, self.perfstats)
  448. else:
  449. if network.thenetwork.snipauthmode == \
  450. network.SNIPAuthMode.THRESHSIG:
  451. for s in DirAuth.endive.enddict['snips']:
  452. # We're just simulating threshold sigs by having
  453. # only the first dirauth sign, but in reality each
  454. # dirauth would contribute to the signature (at the
  455. # same cost as each one signing), so we'll charge
  456. # their perfstats as well
  457. self.perfstats.sigs += 1
  458. DirAuth.consensus.sign(self.sigkey, self.me, self.perfstats)
  459. if network.thenetwork.womode != network.WOMode.VANILLA:
  460. DirAuth.endive.sign(self.sigkey, self.me, self.perfstats)
  461. def received(self, client, msg):
  462. self.perfstats.bytes_received += msg.size()
  463. if isinstance(msg, DirAuthUploadDescMsg):
  464. # Check the uploaded descriptor for sanity
  465. epoch = msg.desc.descdict['epoch']
  466. if epoch != network.thenetwork.getepoch() + 1:
  467. return
  468. # Store it in the class-static dict
  469. if epoch not in DirAuth.uploadeddescs:
  470. DirAuth.uploadeddescs[epoch] = dict()
  471. descstr = str(msg.desc)
  472. if descstr not in DirAuth.uploadeddescs[epoch]:
  473. DirAuth.uploadeddescs[epoch][descstr] = (1, msg.desc)
  474. else:
  475. DirAuth.uploadeddescs[epoch][descstr] = \
  476. (DirAuth.uploadeddescs[epoch][descstr][0]+1,
  477. DirAuth.uploadeddescs[epoch][descstr][1])
  478. elif isinstance(msg, DirAuthDelDescMsg):
  479. # Check the uploaded descriptor for sanity
  480. epoch = msg.desc.descdict['epoch']
  481. if epoch != network.thenetwork.getepoch() + 1:
  482. return
  483. # Remove it from the class-static dict
  484. if epoch not in DirAuth.uploadeddescs:
  485. return
  486. descstr = str(msg.desc)
  487. if descstr not in DirAuth.uploadeddescs[epoch]:
  488. return
  489. elif DirAuth.uploadeddescs[epoch][descstr][0] == 1:
  490. del DirAuth.uploadeddescs[epoch][descstr]
  491. else:
  492. DirAuth.uploadeddescs[epoch][descstr] = \
  493. (DirAuth.uploadeddescs[epoch][descstr][0]-1,
  494. DirAuth.uploadeddescs[epoch][descstr][1])
  495. elif isinstance(msg, DirAuthGetConsensusMsg):
  496. replymsg = DirAuthConsensusMsg(DirAuth.consensus)
  497. msgsize = replymsg.size()
  498. self.perfstats.bytes_sent += msgsize
  499. client.reply(replymsg)
  500. elif isinstance(msg, DirAuthGetConsensusDiffMsg):
  501. replymsg = DirAuthConsensusDiffMsg(DirAuth.consensus)
  502. msgsize = replymsg.size()
  503. self.perfstats.bytes_sent += msgsize
  504. client.reply(replymsg)
  505. elif isinstance(msg, DirAuthGetENDIVEMsg):
  506. replymsg = DirAuthENDIVEMsg(DirAuth.endive)
  507. msgsize = replymsg.size()
  508. self.perfstats.bytes_sent += msgsize
  509. client.reply(replymsg)
  510. elif isinstance(msg, DirAuthGetENDIVEDiffMsg):
  511. replymsg = DirAuthENDIVEDiffMsg(DirAuth.endive)
  512. msgsize = replymsg.size()
  513. self.perfstats.bytes_sent += msgsize
  514. client.reply(replymsg)
  515. else:
  516. raise TypeError('Not a client-originating DirAuthNetMsg', msg)
  517. def closed(self):
  518. pass
  519. if __name__ == '__main__':
  520. # Start some dirauths
  521. numdirauths = 9
  522. dirauthaddrs = []
  523. for i in range(numdirauths):
  524. dirauth = DirAuth(i, numdirauths)
  525. dirauthaddrs.append(dirauth.netaddr)
  526. for a in dirauthaddrs:
  527. print(a,end=' ')
  528. print()
  529. network.thenetwork.nextepoch()