dirauth.py 9.9 KB

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