dirauth.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. val = random.randint(1, self.consdict['totbw'])
  91. idx = bisect.bisect_left(cdf, val)
  92. return self.consdict['relays'][idx-1]
  93. def verify_consensus(consensus, verifkeylist):
  94. """Use the given list of verification keys to check the
  95. signatures on the consensus."""
  96. serialized = consensus.__str__(False)
  97. for i, vk in enumerate(verifkeylist):
  98. vk.verify(serialized.encode("ascii"), consensus.consdict['sigs'][i])
  99. class DirAuthNetMsg(network.NetMsg):
  100. """The subclass of NetMsg for messages to and from directory
  101. authorities."""
  102. class DirAuthUploadDescMsg(DirAuthNetMsg):
  103. """The subclass of DirAuthNetMsg for uploading a relay
  104. descriptor."""
  105. def __init__(self, desc):
  106. self.desc = desc
  107. class DirAuthDelDescMsg(DirAuthNetMsg):
  108. """The subclass of DirAuthNetMsg for deleting a relay
  109. descriptor."""
  110. def __init__(self, desc):
  111. self.desc = desc
  112. class DirAuthGetConsensusMsg(DirAuthNetMsg):
  113. """The subclass of DirAuthNetMsg for fetching the consensus."""
  114. class DirAuthConsensusMsg(DirAuthNetMsg):
  115. """The subclass of DirAuthNetMsg for returning the consensus."""
  116. def __init__(self, consensus):
  117. self.consensus = consensus
  118. class DirAuthGetENDIVEMsg(DirAuthNetMsg):
  119. """The subclass of DirAuthNetMsg for fetching the ENDIVE."""
  120. class DirAuthENDIVEMsg(DirAuthNetMsg):
  121. """The subclass of DirAuthNetMsg for returning the ENDIVE."""
  122. def __init__(self, endive):
  123. self.endive = endive
  124. class DirAuthConnection(network.ClientConnection):
  125. """The subclass of Connection for connections to directory
  126. authorities."""
  127. def __init__(self, peer = None):
  128. super().__init__(peer)
  129. def uploaddesc(self, desc):
  130. """Upload our RelayDescriptor to the DirAuth."""
  131. self.sendmsg(DirAuthUploadDescMeg(desc))
  132. def getconsensus(self):
  133. self.consensus = None
  134. self.sendmsg(DirAuthGetConsensusMsg())
  135. return self.consensus
  136. def getENDIVE(self):
  137. self.endive = None
  138. self.sendmsg(DirAuthGetENDIVEMsg())
  139. return self.endive
  140. def receivedfromserver(self, msg):
  141. if isinstance(msg, DirAuthConsensusMsg):
  142. self.consensus = msg.consensus
  143. elif isinstance(msg, DirAuthENDIVEMsg):
  144. self.endive = msg.endive
  145. else:
  146. raise TypeError('Not a server-originating DirAuthNetMsg', msg)
  147. class DirAuth(network.Server):
  148. """The class representing directory authorities."""
  149. # We simulate the act of computing the consensus by keeping a
  150. # class-static dict that's accessible to all of the dirauths
  151. # This dict is indexed by epoch, and the value is itself a dict
  152. # indexed by the stringified descriptor, with value a pair of (the
  153. # number of dirauths that saw that descriptor, the descriptor
  154. # itself).
  155. uploadeddescs = dict()
  156. consensus = None
  157. endive = None
  158. def __init__(self, me, tot):
  159. """Create a new directory authority. me is the index of which
  160. dirauth this one is (starting from 0), and tot is the total
  161. number of dirauths."""
  162. self.me = me
  163. self.tot = tot
  164. self.name = "Dirauth %d of %d" % (me+1, tot)
  165. # Create the dirauth signature keypair
  166. self.sigkey = nacl.signing.SigningKey.generate()
  167. network.thenetwork.setdirauthkey(me, self.sigkey.verify_key)
  168. network.thenetwork.wantepochticks(self, True, True)
  169. def connected(self, client):
  170. """Callback invoked when a client connects to us. This callback
  171. creates the DirAuthConnection that will be passed to the
  172. client."""
  173. # We don't actually need to keep per-connection state at
  174. # dirauths, even in long-lived connections, so this is
  175. # particularly simple.
  176. return DirAuthConnection(self)
  177. def generate_consensus(self, epoch):
  178. """Generate the consensus (and ENDIVE, if using Walking Onions)
  179. for the given epoch, which should be the one after the one
  180. that's currently about to end."""
  181. threshold = int(self.tot/2)+1
  182. consensusdescs = []
  183. for numseen, desc in DirAuth.uploadeddescs[epoch].values():
  184. if numseen >= threshold:
  185. consensusdescs.append(desc)
  186. DirAuth.consensus = Consensus(epoch, consensusdescs)
  187. def epoch_ending(self, epoch):
  188. # Only dirauth 0 actually needs to generate the consensus
  189. # because of the shared class-static state, but everyone has to
  190. # sign it. Note that this code relies on dirauth 0's
  191. # epoch_ending callback being called before any of the other
  192. # dirauths'.
  193. if self.me == 0:
  194. self.generate_consensus(epoch+1)
  195. del DirAuth.uploadeddescs[epoch+1]
  196. DirAuth.consensus.sign(self.sigkey, self.me)
  197. def received(self, client, msg):
  198. if isinstance(msg, DirAuthUploadDescMsg):
  199. # Check the uploaded descriptor for sanity
  200. epoch = msg.desc.descdict['epoch']
  201. if epoch != network.thenetwork.getepoch() + 1:
  202. return
  203. # Store it in the class-static dict
  204. if epoch not in DirAuth.uploadeddescs:
  205. DirAuth.uploadeddescs[epoch] = dict()
  206. descstr = str(msg.desc)
  207. if descstr not in DirAuth.uploadeddescs[epoch]:
  208. DirAuth.uploadeddescs[epoch][descstr] = (1, msg.desc)
  209. else:
  210. DirAuth.uploadeddescs[epoch][descstr] = \
  211. (DirAuth.uploadeddescs[epoch][descstr][0]+1,
  212. DirAuth.uploadeddescs[epoch][descstr][1])
  213. elif isinstance(msg, DirAuthDelDescMsg):
  214. # Check the uploaded descriptor for sanity
  215. epoch = msg.desc.descdict['epoch']
  216. if epoch != network.thenetwork.getepoch() + 1:
  217. return
  218. # Remove it from the class-static dict
  219. if epoch not in DirAuth.uploadeddescs:
  220. return
  221. descstr = str(msg.desc)
  222. if descstr not in DirAuth.uploadeddescs[epoch]:
  223. return
  224. elif DirAuth.uploadeddescs[epoch][descstr][0] == 1:
  225. del DirAuth.uploadeddescs[epoch][descstr]
  226. else:
  227. DirAuth.uploadeddescs[epoch][descstr] = \
  228. (DirAuth.uploadeddescs[epoch][descstr][0]-1,
  229. DirAuth.uploadeddescs[epoch][descstr][1])
  230. elif isinstance(msg, DirAuthGetConsensusMsg):
  231. client.reply(DirAuthConsensusMsg(DirAuth.consensus))
  232. elif isinstance(msg, DirAuthGetENDIVEMsg):
  233. client.reply(DirAuthENDIVEMsg(DirAuth.endive))
  234. else:
  235. raise TypeError('Not a client-originating DirAuthNetMsg', msg)
  236. def closed(self):
  237. pass
  238. if __name__ == '__main__':
  239. # Start some dirauths
  240. numdirauths = 9
  241. dirauthaddrs = []
  242. for i in range(numdirauths):
  243. dirauth = DirAuth(i, numdirauths)
  244. dirauthaddrs.append(network.thenetwork.bind(dirauth))
  245. for a in dirauthaddrs:
  246. print(a,end=' ')
  247. print()
  248. network.thenetwork.nextepoch()