dirauth.py 26 KB

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