dirauth.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. #!/usr/bin/env python3
  2. import random # For simulation, not cryptography!
  3. import bisect
  4. import nacl.encoding
  5. import nacl.signing
  6. import network
  7. # A relay descriptor is a dict containing:
  8. # epoch: epoch id
  9. # idkey: a public identity key
  10. # onionkey: a public onion key
  11. # addr: a network address
  12. # bw: bandwidth
  13. # flags: relay flags
  14. # vrfkey: a VRF public key (Single-Pass Walking Onions only)
  15. # sig: a signature over the above by the idkey
  16. class RelayDescriptor:
  17. def __init__(self, descdict):
  18. self.descdict = descdict
  19. def __str__(self, withsig = True):
  20. res = "RelayDesc [\n"
  21. for k in ["epoch", "idkey", "onionkey", "addr", "bw", "flags",
  22. "vrfkey", "sig"]:
  23. if k in self.descdict:
  24. if k == "idkey" or k == "onionkey":
  25. res += " " + k + ": " + self.descdict[k].encode(encoder=nacl.encoding.HexEncoder).decode("ascii") + "\n"
  26. elif k == "sig":
  27. if withsig:
  28. res += " " + k + ": " + nacl.encoding.HexEncoder.encode(self.descdict[k]).decode("ascii") + "\n"
  29. else:
  30. res += " " + k + ": " + str(self.descdict[k]) + "\n"
  31. res += "]\n"
  32. return res
  33. def sign(self, signingkey):
  34. serialized = self.__str__(False)
  35. signed = signingkey.sign(serialized.encode("ascii"))
  36. self.descdict["sig"] = signed.signature
  37. def verify_relaydesc(desc):
  38. serialized = desc.__str__(False)
  39. desc.descdict["idkey"].verify(serialized.encode("ascii"), desc.descdict["sig"])
  40. # A consensus is a dict containing:
  41. # epoch: epoch id
  42. # numrelays: total number of relays
  43. # totbw: total bandwidth of relays
  44. # relays: list of relay descriptors (Vanilla Onion Routing only)
  45. # sigs: list of signatures from the dirauths
  46. class Consensus:
  47. def __init__(self, epoch, relays):
  48. relays = [ d for d in relays if d.descdict['epoch'] == epoch ]
  49. self.consdict = dict()
  50. self.consdict['epoch'] = epoch
  51. self.consdict['numrelays'] = len(relays)
  52. self.consdict['totbw'] = sum([ d.descdict['bw'] for d in relays ])
  53. self.consdict['relays'] = relays
  54. def __str__(self, withsigs = True):
  55. res = "Consensus [\n"
  56. for k in ["epoch", "numrelays", "totbw"]:
  57. if k in self.consdict:
  58. res += " " + k + ": " + str(self.consdict[k]) + "\n"
  59. for r in self.consdict['relays']:
  60. res += str(r)
  61. if withsigs and ('sigs' in self.consdict):
  62. for s in self.consdict['sigs']:
  63. res += " sig: " + nacl.encoding.HexEncoder.encode(s).decode("ascii") + "\n"
  64. res += "]\n"
  65. return res
  66. def sign(self, signingkey, index):
  67. """Use the given signing key to sign the consensus, storing the
  68. result in the sigs list at the given index."""
  69. serialized = self.__str__(False)
  70. signed = signingkey.sign(serialized.encode("ascii"))
  71. if 'sigs' not in self.consdict:
  72. self.consdict['sigs'] = []
  73. if index >= len(self.consdict['sigs']):
  74. self.consdict['sigs'].extend([None] * (index+1-len(self.consdict['sigs'])))
  75. self.consdict['sigs'][index] = signed.signature
  76. def bw_cdf(self):
  77. """Create the array of cumulative bandwidth values from a consensus.
  78. The array (cdf) will have the same length as the number of relays
  79. in the consensus. cdf[0] = 0, and cdf[i] = cdf[i-1] + relay[i-1].bw."""
  80. cdf = [0]
  81. for r in self.consdict['relays']:
  82. cdf.append(cdf[-1]+r.descdict['bw'])
  83. # Remove the last item, which should be the sum of all the bws
  84. cdf.pop()
  85. print('cdf=', cdf)
  86. return cdf
  87. def select_weighted_relay(self, cdf):
  88. """Use the cdf generated by bw_cdf to select a relay with
  89. probability proportional to its bw weight."""
  90. totbw = self.consdict['totbw']
  91. if totbw < 1:
  92. raise ValueError("No relays to choose from")
  93. val = random.randint(0, totbw-1)
  94. # Find the rightmost entry less than or equal to val
  95. idx = bisect.bisect_right(cdf, val)
  96. return self.consdict['relays'][idx-1]
  97. def verify_consensus(consensus, verifkeylist):
  98. """Use the given list of verification keys to check the
  99. signatures on the consensus."""
  100. serialized = consensus.__str__(False)
  101. for i, vk in enumerate(verifkeylist):
  102. vk.verify(serialized.encode("ascii"), consensus.consdict['sigs'][i])
  103. class DirAuthNetMsg(network.NetMsg):
  104. """The subclass of NetMsg for messages to and from directory
  105. authorities."""
  106. class DirAuthUploadDescMsg(DirAuthNetMsg):
  107. """The subclass of DirAuthNetMsg for uploading a relay
  108. descriptor."""
  109. def __init__(self, desc):
  110. self.desc = desc
  111. class DirAuthDelDescMsg(DirAuthNetMsg):
  112. """The subclass of DirAuthNetMsg for deleting a relay
  113. descriptor."""
  114. def __init__(self, desc):
  115. self.desc = desc
  116. class DirAuthGetConsensusMsg(DirAuthNetMsg):
  117. """The subclass of DirAuthNetMsg for fetching the consensus."""
  118. class DirAuthConsensusMsg(DirAuthNetMsg):
  119. """The subclass of DirAuthNetMsg for returning the consensus."""
  120. def __init__(self, consensus):
  121. self.consensus = consensus
  122. class DirAuthGetENDIVEMsg(DirAuthNetMsg):
  123. """The subclass of DirAuthNetMsg for fetching the ENDIVE."""
  124. class DirAuthENDIVEMsg(DirAuthNetMsg):
  125. """The subclass of DirAuthNetMsg for returning the ENDIVE."""
  126. def __init__(self, endive):
  127. self.endive = endive
  128. class DirAuthConnection(network.ClientConnection):
  129. """The subclass of Connection for connections to directory
  130. authorities."""
  131. def __init__(self, peer = None):
  132. super().__init__(peer)
  133. def uploaddesc(self, desc):
  134. """Upload our RelayDescriptor to the DirAuth."""
  135. self.sendmsg(DirAuthUploadDescMeg(desc))
  136. def getconsensus(self):
  137. self.consensus = None
  138. self.sendmsg(DirAuthGetConsensusMsg())
  139. return self.consensus
  140. def getENDIVE(self):
  141. self.endive = None
  142. self.sendmsg(DirAuthGetENDIVEMsg())
  143. return self.endive
  144. def receivedfromserver(self, msg):
  145. if isinstance(msg, DirAuthConsensusMsg):
  146. self.consensus = msg.consensus
  147. elif isinstance(msg, DirAuthENDIVEMsg):
  148. self.endive = msg.endive
  149. else:
  150. raise TypeError('Not a server-originating DirAuthNetMsg', msg)
  151. class DirAuth(network.Server):
  152. """The class representing directory authorities."""
  153. # We simulate the act of computing the consensus by keeping a
  154. # class-static dict that's accessible to all of the dirauths
  155. # This dict is indexed by epoch, and the value is itself a dict
  156. # indexed by the stringified descriptor, with value a pair of (the
  157. # number of dirauths that saw that descriptor, the descriptor
  158. # itself).
  159. uploadeddescs = dict()
  160. consensus = None
  161. endive = None
  162. def __init__(self, me, tot):
  163. """Create a new directory authority. me is the index of which
  164. dirauth this one is (starting from 0), and tot is the total
  165. number of dirauths."""
  166. self.me = me
  167. self.tot = tot
  168. self.name = "Dirauth %d of %d" % (me+1, tot)
  169. # Create the dirauth signature keypair
  170. self.sigkey = nacl.signing.SigningKey.generate()
  171. network.thenetwork.setdirauthkey(me, self.sigkey.verify_key)
  172. network.thenetwork.wantepochticks(self, True, True)
  173. def connected(self, client):
  174. """Callback invoked when a client connects to us. This callback
  175. creates the DirAuthConnection that will be passed to the
  176. client."""
  177. # We don't actually need to keep per-connection state at
  178. # dirauths, even in long-lived connections, so this is
  179. # particularly simple.
  180. return DirAuthConnection(self)
  181. def generate_consensus(self, epoch):
  182. """Generate the consensus (and ENDIVE, if using Walking Onions)
  183. for the given epoch, which should be the one after the one
  184. that's currently about to end."""
  185. threshold = int(self.tot/2)+1
  186. consensusdescs = []
  187. for numseen, desc in DirAuth.uploadeddescs[epoch].values():
  188. if numseen >= threshold:
  189. consensusdescs.append(desc)
  190. DirAuth.consensus = Consensus(epoch, consensusdescs)
  191. def epoch_ending(self, epoch):
  192. # Only dirauth 0 actually needs to generate the consensus
  193. # because of the shared class-static state, but everyone has to
  194. # sign it. Note that this code relies on dirauth 0's
  195. # epoch_ending callback being called before any of the other
  196. # dirauths'.
  197. if self.me == 0:
  198. self.generate_consensus(epoch+1)
  199. del DirAuth.uploadeddescs[epoch+1]
  200. DirAuth.consensus.sign(self.sigkey, self.me)
  201. def received(self, client, msg):
  202. if isinstance(msg, DirAuthUploadDescMsg):
  203. # Check the uploaded descriptor for sanity
  204. epoch = msg.desc.descdict['epoch']
  205. if epoch != network.thenetwork.getepoch() + 1:
  206. return
  207. # Store it in the class-static dict
  208. if epoch not in DirAuth.uploadeddescs:
  209. DirAuth.uploadeddescs[epoch] = dict()
  210. descstr = str(msg.desc)
  211. if descstr not in DirAuth.uploadeddescs[epoch]:
  212. DirAuth.uploadeddescs[epoch][descstr] = (1, msg.desc)
  213. else:
  214. DirAuth.uploadeddescs[epoch][descstr] = \
  215. (DirAuth.uploadeddescs[epoch][descstr][0]+1,
  216. DirAuth.uploadeddescs[epoch][descstr][1])
  217. elif isinstance(msg, DirAuthDelDescMsg):
  218. # Check the uploaded descriptor for sanity
  219. epoch = msg.desc.descdict['epoch']
  220. if epoch != network.thenetwork.getepoch() + 1:
  221. return
  222. # Remove it from the class-static dict
  223. if epoch not in DirAuth.uploadeddescs:
  224. return
  225. descstr = str(msg.desc)
  226. if descstr not in DirAuth.uploadeddescs[epoch]:
  227. return
  228. elif DirAuth.uploadeddescs[epoch][descstr][0] == 1:
  229. del DirAuth.uploadeddescs[epoch][descstr]
  230. else:
  231. DirAuth.uploadeddescs[epoch][descstr] = \
  232. (DirAuth.uploadeddescs[epoch][descstr][0]-1,
  233. DirAuth.uploadeddescs[epoch][descstr][1])
  234. elif isinstance(msg, DirAuthGetConsensusMsg):
  235. client.reply(DirAuthConsensusMsg(DirAuth.consensus))
  236. elif isinstance(msg, DirAuthGetENDIVEMsg):
  237. client.reply(DirAuthENDIVEMsg(DirAuth.endive))
  238. else:
  239. raise TypeError('Not a client-originating DirAuthNetMsg', msg)
  240. def closed(self):
  241. pass
  242. if __name__ == '__main__':
  243. # Start some dirauths
  244. numdirauths = 9
  245. dirauthaddrs = []
  246. for i in range(numdirauths):
  247. dirauth = DirAuth(i, numdirauths)
  248. dirauthaddrs.append(network.thenetwork.bind(dirauth))
  249. for a in dirauthaddrs:
  250. print(a,end=' ')
  251. print()
  252. network.thenetwork.nextepoch()