dirauth.py 26 KB

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