dirauth.py 26 KB

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