simulator.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. #!/usr/bin/env python3
  2. import random # For simulation, not cryptography!
  3. import math
  4. import sys
  5. import logging
  6. import resource
  7. import network
  8. import dirauth
  9. import relay
  10. import client
  11. class Simulator:
  12. def __init__(self, relaytarget, clienttarget, statslogger):
  13. self.relaytarget = relaytarget
  14. self.clienttarget = clienttarget
  15. self.statslogger = statslogger
  16. # Some (for now) hard-coded parameters
  17. # The number of directory authorities
  18. numdirauths = 9
  19. # The fraction of relays that are fallback relays
  20. fracfallbackrelays = 0.05
  21. # Mean number of circuits created per client per epoch
  22. self.gamma = 8.9
  23. # Start some dirauths
  24. self.dirauthaddrs = []
  25. self.dirauths = []
  26. for i in range(numdirauths):
  27. dira = dirauth.DirAuth(i, numdirauths)
  28. self.dirauths.append(dira)
  29. self.dirauthaddrs.append(dira.netaddr)
  30. # Start some relays
  31. self.relays = []
  32. for i in range(self.relaytarget):
  33. # Relay bandwidths (at least the ones fast enough to get used)
  34. # in the live Tor network (as of Dec 2019) are well approximated
  35. # by (200000-(200000-25000)/3*log10(x)) where x is a
  36. # uniform integer in [1,2500]
  37. x = random.randint(1,2500)
  38. bw = int(200000-(200000-25000)/3*math.log10(x))
  39. self.relays.append(relay.Relay(self.dirauthaddrs, bw, 0))
  40. # The fallback relays are a hardcoded list of a small fraction
  41. # of the relays, used by clients for bootstrapping
  42. numfallbackrelays = int(self.relaytarget * fracfallbackrelays) + 1
  43. fallbackrelays = random.sample(self.relays, numfallbackrelays)
  44. for r in fallbackrelays:
  45. r.set_is_fallbackrelay()
  46. network.thenetwork.setfallbackrelays(fallbackrelays)
  47. # Tick the epoch to build the first consensus
  48. network.thenetwork.nextepoch()
  49. # Start some clients
  50. self.clients = []
  51. for i in range(clienttarget):
  52. self.clients.append(client.Client(self.dirauthaddrs))
  53. # Throw away all the performance statistics to this point
  54. for d in self.dirauths: d.perfstats.reset()
  55. for r in self.relays: r.perfstats.reset()
  56. for c in self.clients: c.perfstats.reset()
  57. # Tick the epoch to bootstrap the clients
  58. network.thenetwork.nextepoch()
  59. def one_epoch(self):
  60. """Simulate one epoch."""
  61. epoch = network.thenetwork.getepoch()
  62. # Each client will start a random number of circuits in a
  63. # Poisson distribution with mean gamma. To randomize the order
  64. # of the clients creating each circuit, we actually use a
  65. # Poisson distribution with mean (gamma*num_clients), and assign
  66. # each event to a uniformly random client. (This does in fact
  67. # give the required distribution.)
  68. numclients = len(self.clients)
  69. # simtime is the simulated time, measured in epochs (i.e.,
  70. # 0=start of this epoch; 1=end of this epoch)
  71. simtime = 0
  72. allcircs = []
  73. lastpercent = -1
  74. while simtime < 1.0:
  75. allcircs.append(
  76. random.choice(self.clients).channelmgr.new_circuit())
  77. simtime += random.expovariate(self.gamma * numclients)
  78. percent = int(100*simtime)
  79. if percent != lastpercent:
  80. logging.info("Creating circuits in epoch %s: %d%%",
  81. epoch, percent)
  82. lastpercent = percent
  83. # gather stats
  84. totsent = 0
  85. totrecv = 0
  86. dirasent = 0
  87. dirarecv = 0
  88. relaysent = 0
  89. relayrecv = 0
  90. clisent = 0
  91. clirecv = 0
  92. dirastats = network.PerfStatsStats()
  93. for d in self.dirauths:
  94. logging.debug("%s", d.perfstats)
  95. dirasent += d.perfstats.bytes_sent
  96. dirarecv += d.perfstats.bytes_received
  97. dirastats.accum(d.perfstats)
  98. totsent += dirasent
  99. totrecv += dirarecv
  100. relaystats = network.PerfStatsStats()
  101. relaybstats = network.PerfStatsStats()
  102. relaynbstats = network.PerfStatsStats()
  103. for r in self.relays:
  104. logging.debug("%s", r.perfstats)
  105. relaysent += r.perfstats.bytes_sent
  106. relayrecv += r.perfstats.bytes_received
  107. relaystats.accum(r.perfstats)
  108. if r.perfstats.is_bootstrapping:
  109. relaybstats.accum(r.perfstats)
  110. else:
  111. relaynbstats.accum(r.perfstats)
  112. totsent += relaysent
  113. totrecv += relayrecv
  114. clistats = network.PerfStatsStats()
  115. clibstats = network.PerfStatsStats()
  116. clinbstats = network.PerfStatsStats()
  117. for c in self.clients:
  118. logging.debug("%s", c.perfstats)
  119. clisent += c.perfstats.bytes_sent
  120. clirecv += c.perfstats.bytes_received
  121. clistats.accum(c.perfstats)
  122. if c.perfstats.is_bootstrapping:
  123. clibstats.accum(c.perfstats)
  124. else:
  125. clinbstats.accum(c.perfstats)
  126. totsent += clisent
  127. totrecv += clirecv
  128. self.statslogger.info("DirAuths sent=%s recv=%s" % (dirasent, dirarecv))
  129. self.statslogger.info("Relays sent=%s recv=%s" % (relaysent, relayrecv))
  130. self.statslogger.info("Client sent=%s recv=%s" % (clisent, clirecv))
  131. self.statslogger.info("Total sent=%s recv=%s" % (totsent, totrecv))
  132. numdirauths = len(self.dirauths)
  133. numrelays = len(self.relays)
  134. numclients = len(self.clients)
  135. self.statslogger.info("Dirauths %s", dirastats)
  136. self.statslogger.info("Relays %s", relaystats)
  137. self.statslogger.info("Relays(B) %s", relaybstats)
  138. self.statslogger.info("Relays(NB) %s", relaynbstats)
  139. self.statslogger.info("Clients %s", clistats)
  140. self.statslogger.info("Clients(B) %s", clibstats)
  141. self.statslogger.info("Clients(NB) %s", clinbstats)
  142. # Close circuits
  143. for c in allcircs:
  144. c.close()
  145. # Reset stats
  146. for d in self.dirauths: d.perfstats.reset()
  147. for r in self.relays: r.perfstats.reset()
  148. for c in self.clients: c.perfstats.reset()
  149. # Churn relays
  150. # Churn is controlled by three parameters:
  151. # newmean: the mean number of new arrivals per epoch
  152. # newstddev: the stddev number of new arrivals per epoch
  153. # oldprob: the probability any given existing one leaves per epoch
  154. # If target is the desired steady state number, then it should
  155. # be the case that target * oldprob = newmean. That way, if the
  156. # current number is below target, on average you add more than
  157. # you remove, and if the current number is above target, on
  158. # average you add fewer than you remove.
  159. # For relays, looking at all the consensuses for Nov and Dec
  160. # 2019, newmean is about 1.0% of the network size, and newstddev
  161. # is about 0.3% of the network size.
  162. relay_newmean = 0.010 * self.relaytarget
  163. relay_newstddev = 0.003 * self.relaytarget
  164. relay_oldprob = 0.010
  165. # Stop some of the (non-fallback) relays
  166. relays_terminating = []
  167. for r in self.relays:
  168. if not r.is_fallbackrelay and random.random() < relay_oldprob:
  169. relays_terminating.append(r)
  170. for r in relays_terminating:
  171. r.terminate()
  172. self.relays.remove(r)
  173. # Start some new relays
  174. relays_new = int(random.normalvariate(relay_newmean, relay_newstddev))
  175. if relays_new > 0:
  176. for i in range(relays_new):
  177. x = random.randint(1,2500)
  178. bw = int(200000-(200000-25000)/3*math.log10(x))
  179. self.relays.append(relay.Relay(self.dirauthaddrs, bw, 0))
  180. # TODO: churn clients
  181. # Tick the epoch
  182. network.thenetwork.nextepoch()
  183. if __name__ == '__main__':
  184. # Args: womode snipauthmode networkscale numepochs randseed
  185. if len(sys.argv) != 6:
  186. sys.stderr.write("Usage: womode snipauthmode networkscale numepochs randseed\n")
  187. sys.exit(1)
  188. womode = network.WOMode[sys.argv[1].upper()]
  189. snipauthmode = network.SNIPAuthMode[sys.argv[2].upper()]
  190. networkscale = float(sys.argv[3])
  191. numepochs = int(sys.argv[4])
  192. randseed = int(sys.argv[5])
  193. logfile = "%s_%s_%f_%s_%s.log" % (womode.name, snipauthmode.name,
  194. networkscale, numepochs, randseed)
  195. # Seed the PRNG. On Ubuntu 18.04, this in fact makes future calls
  196. # to (non-cryptographic) random numbers deterministic. On Ubuntu
  197. # 16.04, it does not.
  198. random.seed(randseed)
  199. loglevel = logging.INFO
  200. # Uncomment to see all the debug messages
  201. # loglevel = logging.DEBUG
  202. logging.basicConfig(level=loglevel,
  203. format="%(asctime)s:%(levelname)s:%(message)s")
  204. # The gathered statistics get logged separately
  205. statslogger = logging.getLogger("simulator")
  206. handler = logging.FileHandler(logfile)
  207. handler.setFormatter(logging.Formatter("%(asctime)s:%(message)s"))
  208. statslogger.addHandler(handler)
  209. statslogger.setLevel(logging.INFO)
  210. # Set the Walking Onions style to use
  211. network.thenetwork.set_wo_style(womode, snipauthmode)
  212. # The steady-state numbers of relays and clients
  213. relaytarget = math.ceil(6500 * networkscale)
  214. clienttarget = math.ceil(2500000 * networkscale)
  215. # Create the simulation
  216. simulator = Simulator(relaytarget, clienttarget, statslogger)
  217. for e in range(numepochs):
  218. statslogger.info("Starting epoch %s simulation", e+3)
  219. simulator.one_epoch()
  220. maxmemmib = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024
  221. statslogger.info("%d MiB used", maxmemmib)