client.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. #!/usr/bin/env python3
  2. import random # For simulation, not cryptography!
  3. import math
  4. import sys
  5. import logging
  6. import network
  7. import dirauth
  8. import relay
  9. import nacl.hash
  10. class VanillaCreatedExtendedHandler:
  11. """A handler for VanillaCreatedCircuitCell and
  12. VanillaExtendedCircuitCell cells."""
  13. def __init__(self, channelmgr, ntor, expecteddesc):
  14. self.channelmgr = channelmgr
  15. self.ntor = ntor
  16. self.expecteddesc = expecteddesc
  17. self.onionkey = expecteddesc.descdict['onionkey']
  18. self.idkey = expecteddesc.descdict['idkey']
  19. def received_cell(self, circhandler, cell):
  20. secret = self.ntor.verify(cell.ntor_reply, self.onionkey, self.idkey)
  21. enckey = nacl.hash.sha256(secret + b'upstream')
  22. deckey = nacl.hash.sha256(secret + b'downstream')
  23. circhandler.add_crypt_layer(enckey, deckey)
  24. if len(circhandler.circuit_descs) == 0:
  25. # This was a VanillaCreatedCircuitCell
  26. circhandler.replace_celltype_handler(
  27. relay.VanillaCreatedCircuitCell, None)
  28. else:
  29. # This was a VanillaExtendedCircuitCell
  30. circhandler.replace_celltype_handler(
  31. relay.VanillaExtendedCircuitCell, None)
  32. circhandler.circuit_descs.append(self.expecteddesc)
  33. # Are we done building the circuit?
  34. if len(circhandler.circuit_descs) == 3:
  35. # Yes!
  36. return
  37. nexthop = None
  38. while nexthop is None:
  39. nexthop = self.channelmgr.relaypicker.pick_weighted_relay()
  40. if nexthop.descdict['addr'] in \
  41. [ desc.descdict['addr'] \
  42. for desc in circhandler.circuit_descs ]:
  43. nexthop = None
  44. # Construct the VanillaExtendCircuitCell
  45. ntor = relay.NTor(self.channelmgr.perfstats)
  46. ntor_request = ntor.request()
  47. circextendmsg = relay.VanillaExtendCircuitCell(
  48. nexthop.descdict['addr'], ntor_request)
  49. # Set up the reply handler
  50. circhandler.replace_celltype_handler(
  51. relay.VanillaExtendedCircuitCell,
  52. VanillaCreatedExtendedHandler(self.channelmgr, ntor, nexthop))
  53. # Send the cell
  54. circhandler.send_cell(circextendmsg)
  55. class TelescopingCreatedHandler:
  56. """A handler for TelescopingCreatedCircuitCell cells; this will only always
  57. communicate with the client's guard."""
  58. def __init__(self, channelmgr, ntor):
  59. self.channelmgr = channelmgr
  60. self.ntor = ntor
  61. self.onionkey = self.channelmgr.guard.snipdict['onionkey']
  62. self.idkey = self.channelmgr.guard.snipdict['idkey']
  63. def received_cell(self, circhandler, cell):
  64. logging.debug("Received cell in TelescopingCreatedHandler")
  65. secret = self.ntor.verify(cell.ntor_reply, self.onionkey, self.idkey)
  66. enckey = nacl.hash.sha256(secret + b'upstream')
  67. deckey = nacl.hash.sha256(secret + b'downstream')
  68. circhandler.add_crypt_layer(enckey, deckey)
  69. circhandler.replace_celltype_handler(relay.TelescopingCreatedCircuitCell, None)
  70. nexthopidx = None
  71. while nexthopidx is None:
  72. nexthopidx = self.channelmgr.relaypicker.pick_weighted_relay_index()
  73. #print("WARNING: Unimplemented! Need to check if this idx is in the list of circhandlers idxs")
  74. # TODO verify we don't need to do the above
  75. # Construct the TelescopingExtendCircuitCell
  76. ntor = relay.NTor(self.channelmgr.perfstats)
  77. ntor_request = ntor.request()
  78. circextendmsg = relay.TelescopingExtendCircuitCell(
  79. nexthopidx, ntor_request)
  80. # Set up the reply handler
  81. circhandler.replace_celltype_handler(
  82. relay.TelescopingExtendedCircuitCell,
  83. TelescopingExtendedHandler(self.channelmgr, ntor))
  84. # Send the cell
  85. circhandler.send_cell(circextendmsg)
  86. class TelescopingExtendedHandler:
  87. """A handler for TelescopingExtendedCircuitCell cells."""
  88. def __init__(self, channelmgr, ntor):
  89. self.channelmgr = channelmgr
  90. self.ntor = ntor
  91. def received_cell(self, circhandler, cell):
  92. logging.debug("Received cell in TelescopingExtendedHandler")
  93. # Validate the SNIP
  94. dirauth.SNIP.verify(cell.snip, self.channelmgr.consensus,
  95. network.thenetwork.dirauthkeys()[0],
  96. self.channelmgr.perfstats)
  97. onionkey = cell.snip.snipdict['onionkey']
  98. idkey = cell.snip.snipdict['idkey']
  99. secret = self.ntor.verify(cell.ntor_reply, onionkey, idkey)
  100. enckey = nacl.hash.sha256(secret + b'upstream')
  101. deckey = nacl.hash.sha256(secret + b'downstream')
  102. circhandler.add_crypt_layer(enckey, deckey)
  103. circhandler.replace_celltype_handler(
  104. relay.TelescopingExtendedCircuitCell, None)
  105. circhandler.circuit_descs.append(cell.snip)
  106. # Are we done building the circuit?
  107. logging.warning("we may need another circhandler structure for snips")
  108. if len(circhandler.circuit_descs) == 3:
  109. logging.debug("Circuit is long enough; exiting.")
  110. # Yes!
  111. return
  112. nexthopidx = None
  113. guardrange = circhandler.circuit_descs[0].snipdict["range"]
  114. while nexthopidx is None:
  115. # Relays make sure that when the extend to a relay, they are not
  116. # extending to themselves. So here, we just need to make sure that
  117. # this ID is not the same as the guard ID, to protect against the
  118. # guard and exit being the same relay
  119. nexthopidx = self.channelmgr.relaypicker.pick_weighted_relay_index()
  120. if guardrange[0] <= nexthopidx and nexthopidx < guardrange[1]:
  121. # We've picked this relay already. Try again.
  122. nexthopidx = None
  123. # Construct the VanillaExtendCircuitCell
  124. ntor = relay.NTor(self.channelmgr.perfstats)
  125. ntor_request = ntor.request()
  126. circextendmsg = relay.TelescopingExtendCircuitCell(
  127. nexthopidx, ntor_request)
  128. # Set up the reply handler
  129. circhandler.replace_celltype_handler(
  130. relay.TelescopingExtendedCircuitCell,
  131. TelescopingExtendedHandler(self.channelmgr, ntor))
  132. # Send the cell
  133. circhandler.send_cell(circextendmsg)
  134. class SinglePassCreatedHandler:
  135. """A handler for SinglePassCreatedCircuitCell cells."""
  136. def __init__(self, channelmgr, ntor, client_key):
  137. self.channelmgr = channelmgr
  138. self.ntor = ntor
  139. self.client_key = client_key
  140. def received_cell(self, circhandler, cell):
  141. logging.debug("Received cell in SinglePassCreatedHandler")
  142. sys.exit("not yet implemented")
  143. class ClientChannelManager(relay.ChannelManager):
  144. """The subclass of ChannelManager for clients."""
  145. def __init__(self, myaddr, dirauthaddrs, perfstats):
  146. super().__init__(myaddr, dirauthaddrs, perfstats)
  147. self.guardaddr = None
  148. self.guard = None
  149. def get_consensus_from_fallbackrelay(self):
  150. """Download a fresh consensus from a random fallbackrelay."""
  151. fb = random.choice(network.thenetwork.getfallbackrelays())
  152. if network.thenetwork.womode == network.WOMode.VANILLA:
  153. if self.consensus is not None and \
  154. len(self.consensus.consdict['relays']) > 0:
  155. self.send_msg(relay.RelayGetConsensusDiffMsg(), fb.netaddr)
  156. else:
  157. self.send_msg(relay.RelayGetConsensusMsg(), fb.netaddr)
  158. else:
  159. self.send_msg(relay.RelayGetConsensusMsg(), fb.netaddr)
  160. def ensure_guard_vanilla(self):
  161. """Ensure that we have a channel to a guard (Vanilla Onion
  162. Routing version)."""
  163. while True:
  164. if self.guardaddr is None:
  165. # Pick a guard from the consensus
  166. self.guard = self.relaypicker.pick_weighted_relay()
  167. self.guardaddr = self.guard.descdict['addr']
  168. self.test_guard_connection()
  169. if self.guardaddr is not None:
  170. break
  171. logging.debug('chose guard=%s', self.guardaddr)
  172. def test_guard_connection(self):
  173. # Connect to the guard
  174. try:
  175. self.get_channel_to(self.guardaddr)
  176. except network.NetNoServer:
  177. # Our guard is gone
  178. self.guardaddr = None
  179. self.guard = None
  180. def ensure_guard_walking_onions(self):
  181. """Ensure we have a channel to a guard (Walking Onions version).
  182. For the first implementation, we assume an out-of-band mechanism
  183. that just simply hands us a guard; we don't count the number of
  184. operations or bandwidth as this operation in practice occurs
  185. infrequently."""
  186. while True:
  187. if self.guardaddr is None:
  188. #randomly-sample a guard
  189. logging.warning("Unimplemented! guard should be selected from any relays.")
  190. self.guard = self.relaypicker.pick_weighted_relay()
  191. # here, we have a SNIP instead of a relay descriptor
  192. self.guardaddr = self.guard.snipdict['addr']
  193. self.test_guard_connection()
  194. if self.guardaddr is not None:
  195. break
  196. logging.debug('chose guard=%s', self.guardaddr)
  197. def ensure_guard(self):
  198. """Ensure that we have a channel to a guard."""
  199. if network.thenetwork.womode == network.WOMode.VANILLA:
  200. self.ensure_guard_vanilla()
  201. return
  202. # At this point, we are either in Telescoping or Single-Pass mode
  203. self.ensure_guard_walking_onions()
  204. def new_circuit_vanilla(self):
  205. """Create a new circuit from this client. (Vanilla Onion Routing
  206. version)"""
  207. # Get our channel to the guard
  208. guardchannel = self.get_channel_to(self.guardaddr)
  209. # Allocate a new circuit id on it
  210. circid, circhandler = guardchannel.new_circuit()
  211. # Construct the VanillaCreateCircuitMsg
  212. ntor = relay.NTor(self.perfstats)
  213. ntor_request = ntor.request()
  214. circcreatemsg = relay.VanillaCreateCircuitMsg(circid, ntor_request)
  215. # Set up the reply handler
  216. circhandler.replace_celltype_handler(
  217. relay.VanillaCreatedCircuitCell,
  218. VanillaCreatedExtendedHandler(self, ntor, self.guard))
  219. # Send the message
  220. guardchannel.send_msg(circcreatemsg)
  221. return circhandler
  222. def new_circuit_telescoping(self):
  223. """Create a new circuit from this client. (Telescoping Walking Onions
  224. version). If an error occurs and the circuit is deleted from the guard
  225. channel, return None, otherwise, return the circuit handler."""
  226. # Get our channel to the guard
  227. guardchannel = self.get_channel_to(self.guardaddr)
  228. # Allocate a new circuit id on it
  229. circid, circhandler = guardchannel.new_circuit()
  230. # Construct the TelescopingCreateCircuitMsg
  231. ntor = relay.NTor(self.perfstats)
  232. ntor_request = ntor.request()
  233. circcreatemsg = relay.TelescopingCreateCircuitMsg(circid, ntor_request)
  234. # Set up the reply handler
  235. circhandler.replace_celltype_handler(
  236. relay.TelescopingCreatedCircuitCell,
  237. TelescopingCreatedHandler(self, ntor))
  238. # Send the message
  239. guardchannel.send_msg(circcreatemsg)
  240. # Check to make sure the circuit is open before sending it- if there
  241. # was an error when establishing it, the circuit could already be
  242. # closed.
  243. if not guardchannel.is_circuit_open(circid):
  244. logging.debug("Circuit was already closed, not sending bytes. circid: " + str(circid))
  245. return None
  246. # In Telescoping Walking Onions, it should never happen that the
  247. # guard and exit are the same node, as the
  248. # TelescopingExtendedHandler takes care to not pick an index for
  249. # the exit that matches the guard's range. So this test should
  250. # never trigger. In Single-Pass Walking Onions, however, the
  251. # equivalent test is needed here (but should just log a debug,
  252. # not an error, since the client cannot control the index value
  253. # selected for the exit.
  254. if circhandler.circuit_descs[0].snipdict["addr"] == \
  255. circhandler.circuit_descs[2].snipdict["addr"]:
  256. logging.error("CIRCUIT IN A LOOP")
  257. circhandler.close()
  258. circhandler = None
  259. return circhandler
  260. def new_circuit_singlepass(self):
  261. """Create a new circuit from this client. (Single-Pass Walking Onions
  262. version). If an error occurs and the circuit is deleted from the guard
  263. channel, return None, otherwise, return the circuit handler."""
  264. # Get our channel to the guard
  265. guardchannel = self.get_channel_to(self.guardaddr)
  266. # Allocate a new circuit id on it
  267. circid, circhandler = guardchannel.new_circuit()
  268. # first, create the path-selection key used for Sphinx
  269. client_key = nacl.public.PrivateKey.generate()
  270. # Construct the SinglePassCreateCircuitMsg
  271. ntor = relay.NTor(self.perfstats)
  272. ntor_request = ntor.request()
  273. ttl = 2 # TODO set a default for the msg type
  274. circcreatemsg = relay.SinglePassCreateCircuitMsg(circid, ntor_request,
  275. client_key.public_key, ttl)
  276. # Set up the reply handler
  277. circhandler.replace_celltype_handler(
  278. relay.SinglePassCreatedCircuitCell,
  279. SinglePassCreatedHandler(self, ntor, client_key))
  280. # Send the message
  281. guardchannel.send_msg(circcreatemsg)
  282. # Check to make sure the circuit is open before sending it- if there
  283. # was an error when establishing it, the circuit could already be
  284. # closed.
  285. if not guardchannel.is_circuit_open(circid):
  286. logging.debug("Circuit was already closed, not sending bytes. circid: " + str(circid))
  287. return None
  288. return circhandler
  289. def new_circuit(self):
  290. """Create a new circuit from this client."""
  291. circhandler = None
  292. # If an error occured, circhandler will still be None, so we should
  293. # try again.
  294. while circhandler is None:
  295. if network.thenetwork.womode == network.WOMode.VANILLA:
  296. circhandler = self.new_circuit_vanilla()
  297. elif network.thenetwork.womode == network.WOMode.TELESCOPING:
  298. circhandler = self.new_circuit_telescoping()
  299. elif network.thenetwork.womode == network.WOMode.SINGLEPASS:
  300. circhandler = self.new_circuit_singlepass()
  301. return circhandler
  302. def received_msg(self, msg, peeraddr, channel):
  303. """Callback when a NetMsg not specific to a circuit is
  304. received."""
  305. logging.debug("Client %s received msg %s from %s" % (self.myaddr, msg, peeraddr))
  306. if isinstance(msg, relay.RelayConsensusMsg) or \
  307. isinstance(msg, relay.RelayConsensusDiffMsg):
  308. self.relaypicker = dirauth.Consensus.verify(msg.consensus,
  309. network.thenetwork.dirauthkeys(), self.perfstats)
  310. self.consensus = msg.consensus
  311. else:
  312. return super().received_msg(msg, peeraddr, channel)
  313. def received_cell(self, circid, cell, peeraddr, channel):
  314. """Callback with a circuit-specific cell is received."""
  315. logging.debug("Client %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr))
  316. if isinstance(msg, relay.CloseCell):
  317. logging.debug("Log: Client received close cell; closing circuit")
  318. # TODO close cell
  319. return super().received_cell(circid, cell, peeraddr, channel)
  320. class Client:
  321. """A class representing a Tor client."""
  322. def __init__(self, dirauthaddrs):
  323. # Get a network address for client-side use only (do not bind it
  324. # to the network)
  325. self.netaddr = network.NetAddr()
  326. self.perfstats = network.PerfStats(network.EntType.CLIENT)
  327. self.perfstats.name = "Client at %s" % self.netaddr
  328. self.perfstats.is_bootstrapping = True
  329. self.channelmgr = ClientChannelManager(self.netaddr, dirauthaddrs,
  330. self.perfstats)
  331. # Register for epoch tick notifications
  332. network.thenetwork.wantepochticks(self, True)
  333. def terminate(self):
  334. """Quit this client."""
  335. # Stop listening for epoch ticks
  336. network.thenetwork.wantepochticks(self, False)
  337. # Close relay connections
  338. self.channelmgr.terminate()
  339. def get_consensus(self):
  340. """Fetch a new consensus."""
  341. # We're going to want a new consensus from our guard. In order
  342. # to get that, we'll need a channel to our guard. In order to
  343. # get that, we'll need a guard address. In order to get that,
  344. # we'll need a consensus (uh, oh; in that case, fetch the
  345. # consensus from a fallback relay).
  346. guardaddr = self.channelmgr.guardaddr
  347. guardchannel = None
  348. if guardaddr is not None:
  349. try:
  350. guardchannel = self.channelmgr.get_channel_to(guardaddr)
  351. except network.NetNoServer:
  352. guardaddr = None
  353. if guardchannel is None:
  354. logging.debug("In bootstrapping mode")
  355. self.channelmgr.get_consensus_from_fallbackrelay()
  356. logging.debug('client consensus=%s', self.channelmgr.consensus)
  357. return
  358. if network.thenetwork.womode == network.WOMode.VANILLA:
  359. if self.channelmgr.consensus is not None and len(self.channelmgr.consensus.consdict['relays']) > 0:
  360. guardchannel.send_msg(relay.RelayGetConsensusDiffMsg())
  361. logging.debug('got consensus diff, client consensus=%s', self.channelmgr.consensus)
  362. return
  363. # At this point, we are in one of the following scenarios:
  364. # 1. This is a walking onions protocol, and the client fetches the
  365. # complete consensus each epoch
  366. # 2. This is Vanilla Onion Routing and the client doesn't have a
  367. # consensus and needs to bootstrap it.
  368. guardchannel.send_msg(relay.RelayGetConsensusMsg())
  369. logging.debug('client consensus=%s', self.channelmgr.consensus)
  370. def newepoch(self, epoch):
  371. """Callback that fires at the start of each epoch"""
  372. # We'll need a new consensus
  373. self.get_consensus()
  374. # If we don't have a guard, pick one and make a channel to it
  375. self.channelmgr.ensure_guard()
  376. if __name__ == '__main__':
  377. perfstats = network.PerfStats(network.EntType.NONE)
  378. totsent = 0
  379. totrecv = 0
  380. dirasent = 0
  381. dirarecv = 0
  382. relaysent = 0
  383. relayrecv = 0
  384. clisent = 0
  385. clirecv = 0
  386. if len(sys.argv) < 3:
  387. print("Must pass in network mode and snip auth mode!")
  388. print("Network options are vanilla, telescoping, or single-pass.")
  389. print("SNIP auth options are merkle or threshold.")
  390. sys.exit(0)
  391. logging.basicConfig(level=logging.DEBUG)
  392. network_mode = network.WOMode.string_to_type(sys.argv[1])
  393. if network_mode == -1:
  394. print("Not a valid network mode: " + network_mode)
  395. sys.exit(0)
  396. snipauth_mode = network.SNIPAuthMode.string_to_type(sys.argv[2])
  397. if network_mode == -1:
  398. print("Not a valid SNIP authentication mode: " + snipauth_mode)
  399. sys.exit(0)
  400. # Initialize the (non-cryptographic) random seed
  401. random.seed(1)
  402. if network_mode == network.WOMode.VANILLA:
  403. network.thenetwork.set_wo_style(network.WOMode.VANILLA,
  404. network.SNIPAuthMode.NONE)
  405. elif network_mode == network.WOMode.TELESCOPING:
  406. if snipauth_mode == network.SNIPAuthMode.MERKLE:
  407. network.thenetwork.set_wo_style(network.WOMode.TELESCOPING,
  408. network.SNIPAuthMode.MERKLE)
  409. else:
  410. network.thenetwork.set_wo_style(network.WOMode.TELESCOPING,
  411. network.SNIPAuthMode.THRESHSIG)
  412. elif network_mode == network.WOMode.SINGLEPASS:
  413. if snipauth_mode == network.SNIPAuthMode.MERKLE:
  414. network.thenetwork.set_wo_style(network.WOMode.SINGLEPASS,
  415. network.SNIPAuthMode.MERKLE)
  416. else:
  417. network.thenetwork.set_wo_style(network.WOMode.SINGLEPASS,
  418. network.SNIPAuthMode.THRESHSIG)
  419. else:
  420. sys.exit("Received unsupported network mode, exiting.")
  421. # Start some dirauths
  422. numdirauths = 9
  423. dirauthaddrs = []
  424. dirauths = []
  425. for i in range(numdirauths):
  426. dira = dirauth.DirAuth(i, numdirauths)
  427. dirauths.append(dira)
  428. dirauthaddrs.append(dira.netaddr)
  429. # Start some relays
  430. numrelays = 10
  431. relays = []
  432. for i in range(numrelays):
  433. # Relay bandwidths (at least the ones fast enough to get used)
  434. # in the live Tor network (as of Dec 2019) are well approximated
  435. # by (200000-(200000-25000)/3*log10(x)) where x is a
  436. # uniform integer in [1,2500]
  437. x = random.randint(1,2500)
  438. bw = int(200000-(200000-25000)/3*math.log10(x))
  439. relays.append(relay.Relay(dirauthaddrs, bw, 0))
  440. # The fallback relays are a hardcoded list of about 5% of the
  441. # relays, used by clients for bootstrapping
  442. numfallbackrelays = int(numrelays * 0.05) + 1
  443. fallbackrelays = random.sample(relays, numfallbackrelays)
  444. for r in fallbackrelays:
  445. r.set_is_fallbackrelay()
  446. network.thenetwork.setfallbackrelays(fallbackrelays)
  447. # Tick the epoch
  448. network.thenetwork.nextepoch()
  449. dirauth.Consensus.verify(dirauth.DirAuth.consensus, network.thenetwork.dirauthkeys(), perfstats)
  450. print('ticked; epoch=', network.thenetwork.getepoch())
  451. relays[3].channelmgr.send_msg(relay.RelayRandomHopMsg(30), relays[5].netaddr)
  452. # See what channels exist and do a consistency check
  453. for r in relays:
  454. print("%s: %s" % (r.netaddr, [ str(k) for k in r.channelmgr.channels.keys()]))
  455. raddr = r.netaddr
  456. for ad, ch in r.channelmgr.channels.items():
  457. if ch.peer.channelmgr.myaddr != ad:
  458. print('address mismatch:', raddr, ad, ch.peer.channelmgr.myaddr)
  459. if ch.peer.channelmgr.channels[raddr].peer is not ch:
  460. print('asymmetry:', raddr, ad, ch, ch.peer.channelmgr.channels[raddr].peer)
  461. # Start some clients
  462. numclients = 1
  463. clients = []
  464. for i in range(numclients):
  465. clients.append(Client(dirauthaddrs))
  466. # Tick the epoch
  467. network.thenetwork.nextepoch()
  468. # See what channels exist and do a consistency check
  469. for c in clients:
  470. print("%s: %s" % (c.netaddr, [ str(k) for k in c.channelmgr.channels.keys()]))
  471. caddr = c.netaddr
  472. for ad, ch in c.channelmgr.channels.items():
  473. if ch.peer.channelmgr.myaddr != ad:
  474. print('address mismatch:', caddr, ad, ch.peer.channelmgr.myaddr)
  475. if ch.peer.channelmgr.channels[caddr].peer is not ch:
  476. print('asymmetry:', caddr, ad, ch, ch.peer.channelmgr.channels[caddr].peer)
  477. # Pick a bunch of bw-weighted random relays and look at the
  478. # distribution
  479. for i in range(100):
  480. r = relays[0].channelmgr.relaypicker.pick_weighted_relay()
  481. if network.thenetwork.womode == network.WOMode.VANILLA:
  482. print("relay",r.descdict["addr"])
  483. else:
  484. print("relay",r.snipdict["addr"])
  485. relays[3].terminate()
  486. relaysent += relays[3].perfstats.bytes_sent
  487. relayrecv += relays[3].perfstats.bytes_received
  488. del relays[3]
  489. # Tick the epoch
  490. network.thenetwork.nextepoch()
  491. circs = []
  492. for i in range(20):
  493. circ = clients[0].channelmgr.new_circuit()
  494. if circ is None:
  495. sys.exit("ERR: Client unable to create circuits")
  496. circs.append(circ)
  497. circ.send_cell(relay.StringCell("hello world circuit %d" % i))
  498. # Tick the epoch
  499. network.thenetwork.nextepoch()
  500. # See what channels exist and do a consistency check
  501. for r in relays:
  502. print("%s: %s" % (r.netaddr, [ str(k) + str([ck for ck in r.channelmgr.channels[k].circuithandlers.keys()]) for k in r.channelmgr.channels.keys()]))
  503. raddr = r.netaddr
  504. for ad, ch in r.channelmgr.channels.items():
  505. if ch.peer.channelmgr.myaddr != ad:
  506. print('address mismatch:', raddr, ad, ch.peer.channelmgr.myaddr)
  507. if ch.peer.channelmgr.channels[raddr].peer is not ch:
  508. print('asymmetry:', raddr, ad, ch, ch.peer.channelmgr.channels[raddr].peer)
  509. # See what channels exist and do a consistency check
  510. for c in clients:
  511. print("%s: %s" % (c.netaddr, [ str(k) + str([ck for ck in c.channelmgr.channels[k].circuithandlers.keys()]) for k in c.channelmgr.channels.keys()]))
  512. caddr = c.netaddr
  513. for ad, ch in c.channelmgr.channels.items():
  514. if ch.peer.channelmgr.myaddr != ad:
  515. print('address mismatch:', caddr, ad, ch.peer.channelmgr.myaddr)
  516. if ch.peer.channelmgr.channels[caddr].peer is not ch:
  517. print('asymmetry:', caddr, ad, ch, ch.peer.channelmgr.channels[caddr].peer)
  518. if ch.circuithandlers.keys() != \
  519. ch.peer.channelmgr.channels[caddr].circuithandlers.keys():
  520. print('circuit asymmetry:', caddr, ad, ch.peer.channelmgr.myaddr)
  521. for c in circs:
  522. c.close()
  523. for d in dirauths:
  524. print(d.perfstats)
  525. dirasent += d.perfstats.bytes_sent
  526. dirarecv += d.perfstats.bytes_received
  527. print("DirAuths sent=%s recv=%s" % (dirasent, dirarecv))
  528. totsent += dirasent
  529. totrecv += dirarecv
  530. for r in relays:
  531. print(r.perfstats)
  532. relaysent += r.perfstats.bytes_sent
  533. relayrecv += r.perfstats.bytes_received
  534. print("Relays sent=%s recv=%s" % (relaysent, relayrecv))
  535. totsent += relaysent
  536. totrecv += relayrecv
  537. for c in clients:
  538. print(c.perfstats)
  539. clisent += c.perfstats.bytes_sent
  540. clirecv += c.perfstats.bytes_received
  541. print("Client sent=%s recv=%s" % (clisent, clirecv))
  542. totsent += clisent
  543. totrecv += clirecv
  544. print("Total sent=%s recv=%s" % (totsent, totrecv))