client.py 26 KB

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