client.py 25 KB

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