dirauth.py 24 KB

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