client.py 25 KB

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