relay.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/usr/bin/env python3
  2. import random # For simulation, not cryptography!
  3. import math
  4. import nacl.utils
  5. import nacl.signing
  6. import nacl.public
  7. import network
  8. import dirauth
  9. class Relay(network.Server):
  10. """The class representing an onion relay."""
  11. def __init__(self, dirauthaddrs, bw, flags):
  12. self.consensus = None
  13. self.dirauthaddrs = dirauthaddrs
  14. # Create the identity and onion keys
  15. self.idkey = nacl.signing.SigningKey.generate()
  16. self.onionkey = nacl.public.PrivateKey.generate()
  17. self.name = self.idkey.verify_key.encode(encoder=nacl.encoding.HexEncoder).decode("ascii")
  18. # Bind to the network to get a network address
  19. self.netaddr = network.thenetwork.bind(self)
  20. # Our bandwidth and flags
  21. self.bw = bw
  22. self.flags = flags
  23. # Register for epoch change notification
  24. network.thenetwork.wantepochticks(self, True)
  25. self.uploaddesc()
  26. def newepoch(self, epoch):
  27. self.uploaddesc()
  28. def uploaddesc(self):
  29. # Upload the descriptor for the epoch to come
  30. descdict = dict();
  31. descdict["epoch"] = network.thenetwork.getepoch() + 1
  32. descdict["idkey"] = self.idkey.verify_key
  33. descdict["onionkey"] = self.onionkey.public_key
  34. descdict["addr"] = self.netaddr
  35. descdict["bw"] = self.bw
  36. descdict["flags"] = self.flags
  37. desc = dirauth.RelayDescriptor(descdict)
  38. desc.sign(self.idkey)
  39. desc.verify()
  40. descmsg = dirauth.DirAuthUploadDescMsg(desc)
  41. # Upload them
  42. for a in self.dirauthaddrs:
  43. c = network.thenetwork.connect(self, a)
  44. c.sendmsg(descmsg)
  45. c.close()
  46. if __name__ == '__main__':
  47. # Start some dirauths
  48. numdirauths = 9
  49. dirauthaddrs = []
  50. for i in range(numdirauths):
  51. dira = dirauth.DirAuth(i, numdirauths)
  52. dirauthaddrs.append(network.thenetwork.bind(dira))
  53. # Start some relays
  54. numrelays = 10
  55. for i in range(numrelays):
  56. # Relay bandwidths (at least the ones fast enough to get used)
  57. # in the live Tor network (as of Dec 2019) are well approximated
  58. # by (200000-(200000-25000)/3*log10(x)) where x is a
  59. # uniform integer in [1,2500]
  60. x = random.randint(1,2500)
  61. bw = int(200000-(200000-25000)/3*math.log10(x))
  62. Relay(dirauthaddrs, bw, 0)
  63. # Tick the epoch
  64. network.thenetwork.nextepoch()
  65. dirauth.DirAuth.consensus.verify(network.thenetwork.dirauthkeys())
  66. print('ticked; epoch=', network.thenetwork.getepoch())