relay.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/env python3
  2. import nacl.utils
  3. from nacl.signing import SigningKey
  4. from nacl.public import PrivateKey, Box
  5. import network
  6. import dirauth
  7. class Relay(network.Server):
  8. """The class representing an onion relay."""
  9. def __init__(self, dirauthaddrs, bw, flags):
  10. self.consensus = None
  11. self.dirauthaddrs = dirauthaddrs
  12. # Create the identity and onion keys
  13. self.idkey = SigningKey.generate()
  14. self.onionkey = PrivateKey.generate()
  15. # Bind to the network to get a network address
  16. self.netaddr = network.thenetwork.bind(self)
  17. # Our bandwidth and flags
  18. self.bw = bw
  19. self.flags = flags
  20. # Register for epoch change notification
  21. network.thenetwork.wantepochticks(self, True)
  22. self.uploaddesc()
  23. def newepoch(self, epoch):
  24. self.uploaddesc()
  25. def uploaddesc(self):
  26. # Upload the descriptor for the epoch to come
  27. descdict = dict();
  28. descdict["epoch"] = network.thenetwork.getepoch() + 1
  29. descdict["idkey"] = self.idkey.verify_key
  30. descdict["onionkey"] = self.onionkey.public_key
  31. descdict["addr"] = self.netaddr
  32. descdict["bw"] = self.bw
  33. descdict["flags"] = self.flags
  34. desc = dirauth.RelayDescriptor(descdict)
  35. desc.sign(self.idkey)
  36. desc.verify()
  37. descmsg = dirauth.DirAuthUploadDescMsg(desc)
  38. # Upload them
  39. for a in self.dirauthaddrs:
  40. c = network.thenetwork.connect(self, a)
  41. c.sendmsg(descmsg)
  42. c.close()
  43. if __name__ == '__main__':
  44. # Start some dirauths
  45. numdirauths = 9
  46. dirauthaddrs = []
  47. for i in range(numdirauths):
  48. dira = dirauth.DirAuth(i, numdirauths)
  49. dirauthaddrs.append(network.thenetwork.bind(dira))
  50. # Start some relays
  51. numrelays = 10
  52. for i in range(numrelays):
  53. Relay(dirauthaddrs, 500, 0)