dirauth.py 26 KB

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